简体   繁体   中英

how to use dispatch function of useContext hook inside a axios().then()?

in my component

axios({
    method: 'get',
    url: `${SERVER_URL}crawler/get-customer/${uniqueId}`,
}).then(function (response) {
    if(response.data){
        console.log("response",response);
        responseData = response.data;
     dispatch({ type: 'SET_IMG', payload: { url: responseData.logo_url } });
    }
},[]);

response in coming as it should, but the dispatch is being recursive and almost crashed my browser, and the data 'url' is not updated

useEffect(() => {
    axios({
        method: 'get',
        url: `${SERVER_URL}crawler/get-customer/${uniqueId}`,
    }).then(function (response) {
        if(response.data){
           console.log("response",response);
           responseData = response.data;
           props.functionName(response.data);
      }
},[]);

const mapDispatchToProps = dispatch => {
return {
functionName: (data) => dispatch({
        type:'SET_IMG',
        payload: { url: responseData.logo_url }
    })
 }
}

export default connect(, mapDispatchToProps)(nameComponent);

It would help if you could post your whole component, but I'll take a stab anyways...

I'm assuming your component is also taking the fetched data value out of the state (redux?), and then most likely this type of loops is happening:

  • component renders
  • fetch data
  • update value in state (redux?)
  • component renders because value was updated
  • fetch data
  • update value in state
  • etc

Do you intend to only fetch the data once? If you do something like this:

useEffect(() => {
  axios({...}).then(...);
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM