Home > Mobile >  React - Convert this.setState with callback into functional useState
React - Convert this.setState with callback into functional useState

Time:09-06

I have a class component with the method below:

   callBackCatAndSubcat = (values, type) => {
    if (type === 'jobs') {
      this.setState({ jobsSelected: values }, () => (
        this.props.setFieldValue('jobsSelected', _.map(this.state.jobsSelected, (item) => item.id))
      ));
    }
  };

and i'm converting this component into a functional component to use hooks... i'm trying to convert this method, but it isn't working

Current code:

  const [jobsSelected, setJobsSelected] = useState([]);
  const callBackCatAndSubcat = useCallback((items, type) => {
    if (type === 'jobs') {
      setFieldValue('jobsSelected', items.map((item) => item.id));
    }
  }, [setFieldValue]);

I'm not receiving an error, but the function isn't working correctly

CodePudding user response:

Unlike class components, function components do not have a callback when you set state to tell you when the component has been updated. In most cases, I would just call setFieldValue on the next line, using items in the calculation instead of jobsSelected (which you are already doing). The current component will not yet have rerendered, but that's usually not a problem, since the data you need already exists in the variable items.

if (type === 'jobs') {
  setJobsSelected(items);
  setFieldValue('jobsSelected', items.map(item => item.id));
}

If for some reason you must wait until the current component has rerendered, and only then call setFieldValue, you can put the code in a useEffect, to be run after rendering:

const callBackCatAndSubcat = useCallback((items, type) => {
  if (type === 'jobs') {
    setJobsSelected(items);
  }
}, [setFieldValue]);

useEffect(() => {
  setFieldValue('jobsSelected', jobsSelected.map((item) => item.id))
}, [jobsSelected]);
  • Related