简体   繁体   中英

React functional components with hooks - getting response from function written in reducer

Need help in getting response from a function written inside reducer function

functional component

import {
  getAssets,
} from '../../reducers';

    const myFunctionalComponent = (props) => {
    const dispatch = useDispatch();

      const onLinkClick = () => {
        dispatch(getAssets());
      }
    }
    return (
    <div>
    <mainContent />
    </div>
    )
    }

In my reducer

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case ASSETS_LIST: {
      return {
        ...state,
        successToast: true,
        isLoading: false,
        data: action.payload,
      };
    }
}

    export const listsDispactcher = () => dispatch => {
      dispatch({ type: SHOW_LOADER });
      performGet(ENDPOINT URL)
        .then(response => {
          debugger;
          const payload = response.data;
          dispatch({
            type: ASSETS_LIST,
            payload: {
              ...payload,
              data: payload.results,
            },
          });
          dispatch({ type: HIDE_LOADER });
        })
        .catch(err => {
          dispatch({ type: GET_ASSETS_ERROR, payload: err });
          );
        });
    };

when i click the link,am getting my api called in function in reducer and its getting response in newtwork tab in developer console, but how to get the response (that is successToast,data,isLoading )in my functional component and to pass the same to child components?

I advice you to change the structure of your project. Place all your network calls in a file and call them from your component. It is better for readability and understandability

import {
  getAssets,
} from './actions';

    const myFunctionalComponent = (props) => {
    const dispatch = useDispatch();

      const onLinkClick = async () => {
       const data = await dispatch(getAssets());
      }
    }
    return (
    <div>
    <mainContent />
    </div>
    )
    }

In./actions.js

const getAssets =()=>async dispatch =>{
 const res = await axios.get();
 dispatch(setYourReduxState(res.data));
 return res.data;
}

Now your component will get the data of network call. and Your redux state also will get update

For functional components, to access state stored centrally in redux you need to use useSelector hook from react-redux

import React from 'react'
import { useSelector } from 'react-redux'

export const CounterComponent = () => {
  const counter = useSelector(state => state.counter)
  return <div>{counter}</div>
}

Official doc: https://react-redux.js.org/api/hooks#useselector-examples

Also found this working example for you to refer.

https://codesandbox.io/s/8l0sv

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