Problem
Hello to all, I'm tryin to use redux-saga and as the title said I have the error
takeLatest$1 requires a saga parameters
I don't know what I'm missing, and I didn't find anything related on the internet.
Code
Below you will find the file saga/index.js
import {
GET_NEWS_REQUEST,
} from '../types';
import { takeLatest } from 'redux-saga/effects';
import { fetchRecords } from './apiCallSaga';
export default function* root() {
yield takeLatest(GET_NEWS_REQUEST, fetchRecords,);
}
in the same folder I've the file saga/apiCallSaga.js
import { put } from 'redux-saga/effects';
import { getNewsSuccess, getNewsFailed } from '../actions';
function* fetchRecords() {
const url = 'https://newsapi.org/v2/top-headlines?'
try {
const response = yield fetch(url).then(res => res.json());
console.log(response);
yield put(getNewsSuccess(response));
} catch (e) {
yield getNewsFailed();
}
};
export default { fetchRecords };
Expected Behaviour
I need to make the call to a link ( the one provided isn't complete ). This error shouldn't appear.
Well i found the answer.
The problem was
export default
i need only to
export { fetchRecords };
I am having the same error with the reduxsauce package and typescript and I keep landing this question.
export default function* root() {
yield takeLatest(GET_NEWS_REQUEST, fetchRecords,);
}
In order to prevent above from throwing You need to createActions like below;
const {
Types,
Creators
}: CreatedActions<ActionTypes, DefaultActionCreators> = createActions({
getNewsRequest: null
});
Related
I am trying to use react-query to fetch data in getServerSideProps in Next JS but I keep getting this weird error:
Error: Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps` in "/auth/google/callback".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.
Here is my code:
// Packages
import { useRouter } from 'next/router'
import { dehydrate, QueryClient, useQuery } from 'react-query';
// APIs
import { completeGoogleAuth } from '../../../hooks/auth';
export async function getServerSideProps(context) {
const queryClient = new QueryClient()
await queryClient.prefetchQuery('completeGoogleAuth', () => completeGoogleAuth(context.query.code));
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
export default function Callback() {
const router = useRouter();
const { data } = useQuery('completeGoogleAuth', () => completeGoogleAuth(router.query.code))
return (
<>
Loading
</>
)
}
I have tried to use JSON.stringify(dehydrate(queryClient)) and also used JSON.parse(JSON.stringify(dehydrate(queryClient))) but none of them worked.
What can I do?
I stumbled across the same error just today, JSON.stringify(dehydrate(queryClient)) or serializing dehydrate(queryClient) by any means won't really work as the object your completeGoogleAuth function is returning has function values in the key-value pairs, here's a picture of the config object.
And as you know, functions can't be JSON serialized as straightforwardly. Now, what I assume you used(or what I did too) for the completeGoogleAuth fetcher function is use Axios as your API client library. I have found that Axios returns objects that can't be JSON serialized. As a solution, I have just used the native JavaScript fetch() API to get API data and the haven't faced any issues since then.
Here's my fetcher function:
export const getScholarshipInfoSSR = async (token) => {
const response = await fetch(
process.env.NEXT_PUBLIC_API_BASE_URL + portalRoutes.getScholarshipInfo,
{
headers: { Authorization: `JWT ${token}` },
}
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json().then((data) => ({ data }));
};
Here's the prefetched useQuery invocation:
await queryClient.prefetchQuery("portal", () =>
getScholarshipInfoSSR(token)
);
I am trying to display a routerlink name based on a condition. I want to display the div section routerLink name if condition is true.If i check {{isNameAvailable}}, first it displays false and after this.names got the values it shows true.Since in the component getDetails() method is asynchronous this.names getting the values after html template render.Therefore this routerLink does n't display.Therefore I want to display div section after some time. (That 's the solution i have) Don't know whether is there any other solution.
This is my html file code.
<main class="l-page-layout ps-l-page-layput custom-scroll bg-white">
{{isNameAvailable}}
<div class="ps-page-title-head" >
<a *ngIf ="isNameAvailable === true" [routerLink]="['/overview']">{{Name}}
</a>
{{Name}}
</div>
</main>
This is my component.ts file
names= [];
isNameAvailable = false;
ngOnInit() {
this.getDetails()
}
getDetails() {
this.route.params.subscribe(params => {
this.names.push(params.Names);
console.log(this.names);
this.getValues().then(() => {
this.isNameAvailable = this.checkNamesAvailability(this.names);
console.log(this.isNameAvailable);
});
});
}
resolveAfterSeconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 900);
});
}
checkNamesAvailability(names) {
console.log(names);
return names.includes('Sandy');
}
async getValues() {
await this.resolveAfterSeconds(900);
}
And console.log(this.isLevelAvailable); also true. What I can do for this?
1.You do not have anything to show in the HTML only the isNameAvailable, because you do not have any assignment in the Name variable.
2.It is better to use the angular build-in async pipe,
when you want to show the returned value from observables.
3.When you are using the *ngIf directive you can skip *ngIf ="isNameAvailable === true" check because the variable is boolean type, you gust write *ngIf ="isNameAvailable", it will check also for null but NOT for undefined
It is working because the *ngIf directive is responsible for checking and rendering the UI, you can see how many times the directive is checking by calling an function and print and answer in the console.
By any chance do you have changeDetection: ChangeDetectionStrategy.OnPush docs set in component annotation? That might explain this behaviour. With it Angular run change detection only on component #Input()'s changes and since in your case there were non it did not run change detection which is why template was not updated. You could comment that line to check if that was cause of the issue. You are always able to run change detection manually via ChangeDetectorRef.detectChange() docs which should solve you problem
constructor(private cd: ChangeDetectorRef) {}
...
getDetails() {
this.route.params.subscribe(params => {
...
this.getValues().then(() => {
this.isNameAvailable = this.checkNamesAvailability(this.names);
this.cd.detectChanges(); // solution
console.log(this.isNameAvailable);
});
});
}
This stackblitz show this bug and solution. You can read more about change detection here
You could use RxJS timer function with switchMap operator instead of a Promise to trigger something after a specific time.
Try the following
import { Subject, timer } from 'rxjs';
import { takeUntil, switchMap } from 'rxjs/operators';
names= [];
isNameAvailable = false;
closed$ = new Subject();
ngOnInit() {
this.getDetails()
}
getDetails() {
this.route.params.pipe(
switchMap((params: any) => {
this.names.push(params.Names);
return timer(900); // <-- emit once after 900ms and complete
}),
takeUntil(this.closed$) // <-- close subscription when `closed$` emits
).subscribe({
next: _ => {
this.isNameAvailable = this.checkNamesAvailability(this.names);
console.log(this.isNameAvailable);
}
});
}
checkNamesAvailability(names) {
console.log(names);
return names.includes('Sandy');
}
ngOnDestroy() {
this.closed$.next(); // <-- close open subscriptions when component is closed
}
This question is specific to vuejs router, however may simply be a misunderstanding of importing js objects and assigning to the window object.
I am watching for url changes on a page which works fine with the watcher code in the component file. I need to use the same watcher code for multiple components so I extracted it to its own file, assigned it to the global scope, and cannot get it to work. Here are the details:
Working code in with the watcher in the component:
watch:{
$route () {
console.log('route changed')
//was it a reset?
console.log( this.$route.query.sort)
if(this.$route.query.sort === undefined){
if(this.$route.meta.reset){
//reset was pressed... actually do nothing here
this.$route.meta['reset'] = false;
}
else{
this.loading = true;
this.searchableTable.removeResultsTable();
this.searchableTable.options.search_query = this.$route.fullPath;
this.searchableTable.updateSearchPage();
}
}
else
{
//sort change just update the table view
}
}
}
So then I extracted the watch to a file routeWatcher.js:
export default {
$route () {
console.log('route changed')
//was it a reset?
console.log(this.$route.query.sort)
if (this.$route.query.sort === undefined) {
if (this.$route.meta.reset) {
//reset was pressed... actually do nothing here
this.$route.meta['reset'] = false;
}
else {
this.loading = true;
this.searchableTable.removeResultsTable();
this.searchableTable.options.search_query = this.$route.fullPath;
this.searchableTable.updateSearchPage();
}
}
else {
//sort change just update the table view
}
}
}
then I import and use, which works fine....
import searchableTableRouteWatcher from '../../controllers/routeWatcher'
...
watch:searchableTableRouteWatcher
again works fine.
Now the problem - I want to avoid the import in multiple files, so I thought I could put it on the window as a global
in my main.js file:
import searchableTableRouteWatcher from './controllers/routeWatcher'
window.searchableTableRouteWatcher = searchableTableRouteWatcher;
Then in my component:
watch:searchableTableRouteWatcher
results in searchableTableRouteWatcher is not defined
watch:window.searchableTableRouteWatcher
results in no errors, but the code is not being called
I have a feeling it has to do with this and there is confusion on $route()
For your purpose there are 'Mixins' in Vue.js: documentation
What you can do:
create a file, say mixins/index.js:
export const routeWatcher = {
watch: {... your watcher code pasted here ... }
};
import into your component:
import { routeWatcher } from 'path/to/mixins/index';
add mixin to your component properties and methods:
<script>
export default {
mixins: [routeWatcher];
data () ...... all your original component's script content
}
Mixin's content will be merged with component's original properties and act if it was hardcoded there.
Addition after your comment:
You can also declare Mixin globally, like this:
above 'new Vue' declaration put this code:
Vue.mixin({
watch: {....}
});
This mixin will appear in every component.
I'm trying to parse a json received from external api.
My reducer is:
import { RECEIVED_FORECAST } from '../actions/index';
export default function ForecastReducer (state = [], action) {
switch (action.type) {
case RECEIVED_FORECAST:
return Object.assign({}, state, {
item: action.forecast
})
default:
return state;
}
}
Then main reducer goes like:
import { combineReducers } from 'redux';
import ForecastReducer from './forecast_reducer';
const rootReducer = combineReducers({
forecast: ForecastReducer
});
export default rootReducer;
and container looks like
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
class WeatherResult extends Component {
render() {
const forecast = this.props.forecast.item;
{console.log('almost: ', forecast)}
return (
<div>
<h1> </h1>
</div>
)
}
}
function mapStateToProps({ forecast }) {
return {
forecast
}
}
export default connect(mapStateToProps)(WeatherResult)
Output of the almost is exactly the same son as I supposed:
almost:
Object
currently: {time: 1476406181, summary: "Drizzle", icon: "rain", nearestStormDistance: 0, precipIntensity: 0.0048, …}
daily: {summary: "Light rain on Saturday and Thursday, with temperatures rising to 92°F on Wednesday.", icon: "rain", data: Array}
So, my question is, how can I show the value of, let's say forecast.currently.summary?
1) If I just try to insert it within {} I receive : 'TypeError: undefined is not an object (evaluating 'forecast.currently')'
2) I can't use mapping as the json might have other components added
Is there any method to get to this property directly, without mapping all the file?
Thanks
The problem you have is that you're requesting the data. That doesn't complete immediately. Think about what the app is doing while you're waiting for the weather data to arrive.
It's displaying something. In your case, the render method is failing because you're trying to show data that hasn't arrived yet.
The solution:
render() {
const forecast = this.props.forecast;
const text = forecast && forecast.item.currently.summary || 'loading...';
return (
<div>
<h1>{text}</h1>
</div>
)
}
}
This way you check if you already have the data and if not, you show something useful.
I would like to retrieve the current params outside of a component, and as far as I can tell React Router does not provide a convenient way of doing that.
Sometime back before 0.13 the router had getCurrentParams() which is what I used to use.
Now the best thing I can figure out is:
// Copy and past contents of PatternUtils into my project
var PatternUtils = require('<copy of PatternUtils.js>')
const { remainingPathname, paramNames, paramValues } =
PatternUtils.matchPattern(
"<copy of path pattern with params I am interested in>",
window.location.pathname);
Is there a way to do this with React router?
you could use matchPath:
import { matchPath } from 'react-router'
const { params }= matchPath(window.location.pathname, {
path: "<copy of path pattern with params I am interested in>"
})
If you use matchPath(window.location.pathname, ...) within your render function, your component won't signal to be re-rendered on route changes. You can instead use react router's useLocation hook to fix this:
import { matchPath } from 'react-router'
import { useLocation } from 'react-router-dom'
function useParams(path) {
const { pathname } = useLocation()
const match = matchPath(pathname, { path })
return match?.params || {}
}
function MyComponent() {
const { id } = useParams('/pages/:id')
return <>Updates on route change: {id}</>
}
Note: matchPath will return null for paths which don't match.
If you use the object destructure pattern { params } = matchPath it may throw the following error:
Cannot destructure property 'params' of 'Object(...)(...)' as it is null.