Кріс
Кріс

Reputation: 167

function with second argument react hooks

all i want is, after changing the state, i want to run the second argument..

without hooks.. this is what it looks like

state = {
  gasTypeFrom: '',
}

setModal = item => {
    setState({ gasType: item }, () => {
      renderFrom();
    });
  };

this is what i tried with hooks

 const [froms, setFroms] = useState({
    gasType: 'Select Value Here',
    displayModal: false,
  });

function setModalFrom(item) {
    useEffect(
      () => {
        setFroms({...froms, gasType: item});
      },
      () => {
        renderModalFrom();
      }
    );
    console.log('setModalFrom()', froms.gasType);
  }

how do i do it in hooks with a second argument?

Upvotes: 0

Views: 184

Answers (1)

Drew Reese
Drew Reese

Reputation: 202667

useEffect takes a function callback and a dependency array, so when a value in the dependency array is updated the effect is fired.

const [froms, setFroms] = useState({
  gasType: 'Select Value Here',
  displayModal: false,
});

useEffect(() => {
  renderModalFrom();
}, [froms]); // when a value here updates, effect is run

...somewhere in your code
setFroms({...froms, gasType: item}); // this updates the value

useEffect documentation

Upvotes: 1

Related Questions