简体   繁体   中英

How to save the response info in the Redux state after fetch into useEffect hook?

I have the following case:

 export default function Names() { const dispatch = useDispatch(); const [names, setNames] = useState([]); const stateNames = useSelector(state => state.names); const fetchNames = async () => { try { const response = await nameService.getNames(); dispatch(initNames(response.body)); setNames(response.body); } catch (error) { console.error('Fetch Names: ', error); } }; useEffect(() => { fetchNames(); }, []); return ( { names.map((name, index) => ( <Tab label={ budget.label} key={index}/> )) } ); }

When my component is rendered in the browser console I get a warning: "React Hook useEffect has a missing dependency: 'fetchBudgets'. Either include it or remove the dependency array react-hooks / exhaustive-deps". If I comment the line in which I write the names in Redux state, the warning does not appear. I need the list of names in the state so that I can update the list when a new name is written to the list from the outside.

export default function AddNameComponent() {
  const dispatch = useDispatch();
  const [label, setLabel] = useState('');
  const [description, setDescription] = useState('');

  const onLabelChange = (event) => { setLabel(event.target.value); };
  const onDescriptionChange = (event) => { setDescription(event.target.value); };

  const handleSubmit = async (event) => {
    try {
      event.preventDefault();
      const newName = {
        label: label
        description: description
      };
      const answer = await budgetService.postNewName(newName);
      dispatch(add(answer.body)); // Adding new Name in to Redux state.names
    } catch (error) {
      setErrorMessage(error.message);
      console.error('Create Name: ', error);
    }
  };

  return (
    <div>
      // Create name form
    </div>
  )
}

This is how everything works, but I don't understand why I have a warning. I tried to add a flag to the array with dependencies of usеЕffect. I tried to pass the function 'fetchNames' through the parent component - in props and to add it as a dependency, but it is executed twice... Can you advise please!

It's just an eslint warning so you don't have to fix it. But basically any variables which are used in the useEffect function are expected to be included in the dependency array. Otherwise, the effect will never be re-run even if the function fetchBudgets were to change.

It is expecting your hook to look like

useEffect(() => {
    fetchBudgets();
}, [fetchBudgets]);

Where the effect will run once when the component is mounted and run again any time that the fetchBudgets function changes (which is probably never).

If it's executing more than once, that means that fetchBudgets has changed and you should try to figure our where and why it has been redefined. Maybe it needs to be memoized?

Here are the docs on putting functions in the dependency array.

Thanks for your attention. I tried many options and finally found one solution.

    useEffect(() => {
    async function fetchNames() {
      const response = await nameService.getNames();
      dispatch(init(response.body));
      setNames(response.body);
    }

    fetchNames();
  }, [dispatch, props]);

I put 'props' in an array of dependencies for one useEffect execution.

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