score:1

you aren't far off in your attempt.

there are two problems:

problem 1.

in order to get the same effect as componentwillmount (side note - this is a deprecated method, use componentdidmount or the constructor) you need to tell the useeffect to only run once on mount. to do this you give it an empty array of dependencies.

useeffect(() => {
// do stuff
}, []); // empty array as second argument

by not giving a second argument, the effect will run every single render.

problem 2.

state updates are asynchronous. this means you cannot console log apiresponse immediately after updating it and expect it to contain the new value.

to get around this, just console.log inside the function body outside of the hook.

here is a simplified example:

const {usestate, useeffect} = react;

const example = () => {
  const [apiresponse, setapiresponse] = usestate();
  
   useeffect(() => {
     const fetchapiresponse = () => {
       const result = 'test';
       setapiresponse(result);
       // will not be updated
       console.log("wrong: apiresponse ", apiresponse);
     }
     fetchapiresponse();
   }, []);
   
   // will be updated
   console.log("right: apiresponse ", apiresponse);
   
   return <span />
}

reactdom.render(<example />, document.getelementbyid('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>


Related Query

More Query from same tag