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>
Source: stackoverflow.com
Related Query
- Converting React Functional Component to Hook
- Converting stateful React component to stateless functional component: How to implement "componentDidMount" kind of functionality?
- useParams hook returns undefined in react functional component
- Converting React class with "static get defaultProps()" to functional component
- Converting dash's(plotly) react functional component into class component
- React Render prop with Children in a functional component with useState Hook
- Converting class component to functional component using react hooks (useRef)—how to avoid "undefined" error
- Elements not displaying with .map() in react functional component with useEffect hook
- Get React Hook Value from outside the functional component
- How to use useHistory() hook outside functional component in React js?
- How to call a react hook fetch request in a functional component to access data then pass to a class component to map?
- React update state hook on functional component does not allow dot notation
- Get id using useParams hook in functional component - react router dom v6
- React functional component useEffect hook with dependency equal in class component lifecycles
- Checkbox state not updating in react Hook functional component
- Passing React Hook to functional component
- Converting React class based component to functional component
- React call from class to functional component. Error: Invalid hook call. Hooks can only be called inside of the body of a function component
- React functional component using the `useState` hook does not update onChange using ReactiveSearch
- How to pass hook function to react functional component
- Converting react class component to functional component, rendering perfectly but functionality lost?
- Why doesn't memoization of a React functional component call with useMemo() hook work?
- Calling a state update function within a state update function - useState hook in React Functional component
- How can I expose React Hook outside of my React Functional Component
- Converting Class Component to Functional Component in React
- Converting React class component to functional component with hooks : Problem with event listeners
- snapshot testing react functional component useSelctor hook
- converting react class to functional component with refs
- Converting React Class component to Function Component With Hook
- Dev tools show many websocket requests of chat app built by react hook with functional component
More Query from same tag
- How to ensure an event listener is always called inside a ReactJS child component?
- How to correctly call function from component in another component
- Reference id into array and map it
- Is it possible to map with multiple items?
- material-ui layout, breakpoints on containers
- Redirection In React-Router-Dom v6
- Getting a substring from a message of string to push in array
- Creating Sticky Navbar with drop shadow in React js
- React Hooks - set last value?
- Warning: An update to App inside a test was not wrapped in act(...) in enzyme and hooks
- How to evaluate the passed prop to the styled component using react and typescript?
- Add css class onClick to idividual elements generated by mapping an array in React
- passing id through Link to getServerSideProps :next js
- Passing parameters to onClick function received via props without binding this
- react progress bar not dynamic
- adding checkboxes value in react router dom urls
- cannot configure react-router to run on plunkr
- Call a function on state change *and* on button click
- How can I access query parameters with react router?
- React: Read Zip file using JSZip from the project directory
- React 'Hello World' not loading
- Need help solving a React Typescript error
- How to correctly wait for fetch in a react class
- In React, how would you dynamically render a component?
- Geeting value differance in MUI date picker
- react warning cannot set state when using promises
- Normalize an array of objects in the flattest way for the Redux?
- I'm getting a Cannot read property of 'exercises' of undefined error when trying to map my props
- Make button behave like checkbox in React
- How can I delete cart item on index using Redux?