nico
Published in : 2022-03-30

Best way to update the state in one class component from the redux store?

React js

Hello I need to use the the state in one class component for the react sortable tree.

But I use axios, thunk and redux to get the data.

So what is the best way to get the result of redux store data updated by ajax with axios to the state of my class component each time ?

Basically each time i click “search” it will send action to redux which updates the store, I need then a good way to update the component state from the store.

Thanks for your advice.

Comments

nico Date : 2022-03-30

Best answers

4

Best answers

4

As far as I am concerned there are two ways:

- getDerivedStateFromProps : which allows us to return the new state from the new prop

state = { MyData: xxx}static getDerivedStateFromProps(props, state) { return { MyData: props.MyData, };}

I don't really like it as it is static and we can't use anything in my class component…

- componentDidUpdate : which allows us to get the new props and we can compare with the previous props, then we can use this.setState()

 

componentDidUpdate(props) { const { MyData } = this.props if (props.MyData !== MyData ) { this.setState({ MyData : props.MyData })) }}

It is not perfect as we need to setState which calls render again.. so it s less smooth and for performance reason it is a shame too

Mohamed Atef Date : 2022-03-30

Great solution, I was about to ask How you did it, Great job

nico Date : 2022-03-31

Best answers

4

Best answers

4

Thanks for your feedback :)

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Could not be processed as an image because it has an invalid content type
Publish date: 2021-12-08 | Comments: 0

Tag: React js

[solved] useEffect is repeating the request Reactjs
Publish date: 2022-04-07 | Comments: 2

Tag: React js

Warning: React.jsx: type is invalid
Publish date: 2022-05-06 | Comments: 1

Tag: React js

import link as router link from 'react-router-dom' Reactjs
Publish date: 2021-09-30 | Comments: 3

Tag: React js

Reload browser window using Reactjs?
Publish date: 2022-02-08 | Comments: 4

Tag: React js

How to get the selected object in "Autocomplete material ui"?
Publish date: 2021-12-22 | Comments: 3

Tag: React js

React Redux : Connect is not called
Publish date: 2022-03-02 | Comments: 1

Tag: React js