I have this function that is in the top level component that I'd like to reuse but on a different piece of state. In the following code sample, I'm using it on userData, but I'd like to be able to reuse it on a piece of state called repoData, either within the same component it's child, or outside. Just not sure how to go about it, since, if I do something like pass it the states as args, setting the state would throw an error because it would look like: this.setState({this.state.userData: data}).
fetchUserData(params) {
fetch('https://api.github.com/users/' + params)
.then(response => {
if (!response.ok) {
throw Error("Network failure")
}
return response;
})
.then(data => data.json())
.then(data => {
this.setState({
userData: data
})
}, () => {
this.setState({
requestFailed: true
})
})
}
Your question is more about refactoring your code I believe. Here you can look at it as moving out the logic of fetching user data asynchronously. Your component need not know who(fetch, axios) is doing the work of fetching the data for it. Also it is not required for a component to know from where(https://api.github.com/users/' + params) to get this data.
One possible way of doing it is to move your fetch call in a separate function which will return the data to your component after fetching it asynchronously. Then it is responsibility of component to handle the data the way it want to.
So as you can see the key point here is identifying and separating out the responsibilities of each piece of code. Advantages of doing this will be clean code structure, less number of lines, maintainable code and most importantly easily testable code.
I hope this solves your problem. If you are interested to learn about such techniques more you can read about DRY principle and refactoring techniques.
Edit 1:
I have created this code sample for your reference
What are JavaScript Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Some samples for fetch: https://davidwalsh.name/fetch
I personally recommend using axios. You can see comparison of fetch and axios here: https://medium.com/#thejasonfile/fetch-vs-axios-js-for-making-http-requests-2b261cdd3af5
If I'm understanding you correctly
you should move the function to a file x.js
it should accept an other param which is the name of the new (piece) of state
it should also accept a param for the this.setState of the component calling it.
import it and use it in componentDidMount as normal
```
export const fetchUserData(params,setState , stateParam) {
fetch('https://api.github.com/users/' + params)
.then(response => {
if (!response.ok) {
throw Error("Network failure")
}
return response;
})
.then(data => data.json())
.then(data => {
setState({
[stateParam]: data
})
}, () => {
setState({
requestFailed: true
})
})
}
you can call it as follows
import { fetchUserDate } from "./path/to/x"
fetchUserDate("param" , this.setState, "xOnState")
Related
I have a problem with a simple function which where I want to call an API and then do something with the response. Basically, I just want to set my react component state to the response I get and then navigate to the other page The problem is that my code executes another part of the function before an API call is finished, and I end up on another page with console.log of undefined
There is my function:
const startNewGame = () => {
GameService.startGame()
.then((response) => {
setGame(response.data);
console.log(game);
navigate('intro');
})
.catch((e) => {
console.log(e);
});
};
I can wrap my navigate into if(!game !== undefined) but then I have to click two or more times on a button.
Thank you all guys for help :)
You probably do several things incorrect at the same time, so to understand what exactly is wrong might take some time. Take these steps to debug your code:
Make each .then call do only one thing (and stick to that principle in other cases). You could chain as many .then as you like. Moreover you could return data from one .then to the next, so your code might look like this:
GameService.startGame()
.then(response => response.data)
.then(data => {
setGame(data)
})
.then(() => {
console.log(game);
navigate('intro');
})
.catch((e) => {
console.log(e);
});
Understand your components composition. Where exactly are you saving your response? is it just local component useState or some Context Api state that wraps the app? When you navigate to "other page" your "current page" state will be unavailable to "other page" unless you keep the data somewhere up in the tree when both pages could access that.
For further references keep in mind that setGame is asynchronous, so you need to wait for the state to be updated to make sure that its updated.
Try this:
const startNewGame = () => {
GameService.startGame()
.then((response) => {
setGame(response.data);
// game is not updated yet
// console.log(game); <- Remove this line
// navigate('intro'); <- Remove this line
})
.catch((e) => {
console.log(e);
});
};
useEffect(()=>{
if(game !== undefined){
navigate('intro')
}
}, [game])
I am new in vue js . I want to call api . it is perfectly working. but i want to put condition on that if api response is this than vue js array is updated .
this is my code . but it gives me error "do not mutate vuex store state outside mutation handlers."
How to handle this?
axios.post(baseUrl+'/api/v1/addProductWishlist',pitem,
{headers: {
'Authorization': 'Bearer ' + x,
'Content-Type':'application/json'
}
}).then(r => {
if(r.data.status == 202)
{
}
else{
state.cartItems.push(payload);
}
});
use Mutation to modify state, do not redirect change state instance
for more detail: https://vuex.vuejs.org/guide/mutations.html
Notice that you don't follow the correct pattern of using Vuex.
You should update the state ONLY from within a mutation. It is an important part in state management in Vuex (as well as in other frameworks). Not following this concept might break the reactivity Vuex maintains and make a big app extremely unpredictable since you can't follow which part of the app have changed a value in your state.
A good practice would be to separate mutations, actions and api calls to 3 different files. The action might be your functionality manager - create an action that calls the api file function (that only executes the axios api call), and after getting back the response calling the mutation from the mutations file to update the state accordingly.
// actions.js
{
myAction: async ({ commit }) => {
const response = await myApiCall();
if (response.data.status == 202) { ... }
else {
commit('ADD_CART_ITEM', response.item)
}
}
}
// api.js
export function myApiCall() {
return axios.post(...)
}
// mutations.js
{
ADD_CART_ITEM: (state, payload) => state.cartItems.push(payload);
}
I have the following code:
componentDidMount () {
fetch('/data')
.then(res => res.json())
.then(data => this.setState({data}));
this.countVar();
}
countVar () {
//iterate through this.state.data and filter out certain values
}
The countVar() function isn't loading inside componentDidMount(). When I did console.log(this.state.data) right after the componentDidMount()-function, it returned an empty array, so I guess that's the reason.
I tried to use componentDidUpdate() instead if countVar(), but I didn't consider that that would create an infinite loop. I don't quite know how to handle this.
The data that I'm fetching consists of several object arrays. in countVar() I'm filtering out a certain object array, hence the structure of my functions.
Does anyone know how I could solve this problem?
fetch('/data')
.then(res => res.json())
.then(data => this.setState({data}));
This code is async. This means that when the fetch is complete, it will run the functions passed into the then callback. You're running your iteration function directly after registering the promise; not after the promise is resolved.
ALSO
this.setState is not synchronous. You can't guarantee that after you request that the state is set, it is set. It is set some time afterward, but React provides an option for this; you pass in a callback function once state setting is complete.
this.setState({ data }, () => console.log('do something'))
You should call this.countVar inside the then of the Promise otherwise it will run before the fetch Promise is over.
Like this:
componentDidMount () {
fetch('/data')
.then(res => res.json())
.then(data => {
this.setState({data}, this.countVar);
});
}
I'm running this.countVar as a callback to setState so that it runs once setState is done.
I am currently building a web app which contains a menu. The menu can change depending on a couple of variables, and so I make a call to an api, to request the correct menu items that should be shown.
server.get('/api/getMenu', (req, res) => {
getMenu((err, content) => {
if(!err) {
res.send(content);
} else {
res.status(500).send();
}
})
});
This request is working perfectly fine, and I am then dispatching an action that will call this API on componentWillMount
export function fetchMenuItems() {
return (dispatch) => {
fetch('/api/getMenu')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((results) => dispatch(fetchSuccess(results)))
}
}
export function fetchSuccess(results) {
return {
type: 'FETCH_SUCCESS',
menuItems: results
};
}
This again is working fine and loading the menu items, however it looks strange as the menu items seem to render on the page after the rest of the page has already loaded (I'm assuming due to how long the request takes).
Is there any way to preload the menu items before the whole page actually renders? I've heard of promises but know little of them, would this potentially be a solution?
I'm assuming you're looking for componentWillMount react lifecycle method.
componentWillMount will be invoked only once right before your component rendered at the first time. This is a perfect place to put any pre-loading data logic.
Hope this helps.
So I've been building an app that uses the Fetch API to make a request. Unfortunately, I think the code shown in the Facebook docs are (may be?) incorrect.
Problem
When starting the app, Fetch makes a call to a URL to pull JSON data.
componentDidMount(){
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: JSON.stringify(responseJson)
})
})
.catch((error) => {
console.error(error);
});
}
This is similar to the code that Facebook docs give as an example.
The problem is that when I start the app, the data doesn't render in the render function.
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
var data = this.state.data;
return this.renderData(data);
}
At least, it doesn't render until after I click/touch the screen. Once I touch the screen, the data renders. Otherwise, it just stays in a perpetual "loading" state.
Solution?
I remembered that sometime in the past, I had to bind event handlers to their respective controls (this.handleClick = this.handleClick.bind(this), for example)
And that got me thinking: Where is this in the promise request? Where does this point to?
componentDidMount(){
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({ <--- **Where are you going?**
isLoading: false,
data: JSON.stringify(responseJson)
})
})
I console.logged "this" within the responseJson promise, and it does point to the component, but I'm not convinced. With it being buried inside of the promise, I don't think the this.setState function is actually able to set the component's State.
So I made a variable before the fetch request.
const that = this;
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
that.setState({
isLoading: false,
data: JSON.stringify(responseJson)
})
})
Now I'm not a software guru. I've been teaching myself this stuff for the last couple of years, so my logic is off half the time.
So if my reasoning is correct or incorrect, please let me know! What I do know is that this is working for me; once the data is fetched, it automatically sets the state and reloads, showing me the JSON data when rendered.
Any thoughts? Am I completely off here? Am I missing anything?
I saw a problem like yours. It's not about your code. Are using the app in the Remote JS debugging mode? If so, disable it. If it didn't work, try to install a release version.
(Posted on behalf of the OP).
Apparently it was due to running the app in debug mode. Running the app with this.setState works just fine when not in debug mode.