I'm making a to-do list in React. The items are stored in an object in the app's state. When the user checks the box, I can update the state, but not display the updated state. I know that changes to the state do not always immediately update the component, so I've tried passing the render() function as a callback to the setState() function, but I get an error saying Invalid argument passed as callback. Expected a function. Instead received: [object Object]. I've also tried adding the componentDidUpdate() function but didn't have any success using that method because I don't understand how it's triggered. How can I update the state then immediately display the updated state on the page?
So far what I have it this function which is triggered when a checkbox is checked/unchecked.
constructor(props) {
super(props);
this.state = {
isLoading: null,
isDeleting: null,
list: null,
title: "",
term: "",
content: []
};
}
async componentDidMount() {
try {
const list = await this.getList();
const { title, content } = list;
this.setState({
list,
title,
content
});
} catch (e) {
alert(e);
}
}
checkedChange = async event => {
let todos = Object.assign({}, this.state.content);
let key = event.target.attributes[0].value;
if(event.target.checked) {
todos[key] = true;
this.setState({todos});
}
else {
todos[key] = false;
this.setState({todos});
}
};
The syntax this.setState({todos}) is shorthand equivalent to writing this.setState({todos: todos}). So you are not updating this.state.content which I suspect is what you want to be doing. So try this.setState({content: todos}).
Edit: I highly recommend you install and use the Chrome React developer tools. It will show up in your dev tray as a tab next to Console, Inspector, etc. It is extremely useful for debugging and visualizing what's going on in your components.
Related
I'm very new to React, what I'm trying to achieve is that when I click on a button my location gets detected and updates the state, I've tried doing this however for some reason it is not updating my state, I've searchedall over the internet but couldn't find a solution that matches my business. Your assistance is much appreciated.
this.state = { coordinatesList: [123, 456], [567, 891] }
<button onClick={this.addCurrentLocation}></button>
addCurrentLocation() {
var coordinatesList = this.state.coordinatesList;
console.log("coordinatesList ", coordinatesList)
navigator.geolocation.getCurrentPosition((position) => {
coordinatesList.push([position.coords.latitude, position.coords.longitude]); ==> this doesn't work
})
// coordinatesList.push([123, 456]); ===> this works
this.setState({
coordinatesList
})
}
Your problem is that getCurrentPosition is async so you would have to place the setState inside the callback, otherwise setState gets called before the getCurrentPosition ends.
addCurrentLocation() {
var coordinatesList = this.state.coordinatesList;
navigator.geolocation.getCurrentPosition((position) => {
coordinatesList.push([position.coords.latitude, position.coords.longitude]);
this.setState({
coordinatesList
})
})
}
I'm trying to set a state of the user by getting a value from my database and then using it. For some reason the state does not update itself I have tried await and async. What other options exists if this one can't be reliable to make this be a value.
I do get the following error : Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
- node_modules/fbjs/lib/warning.js:33:20 in printWarning
- node_modules/fbjs/lib/warning.js:57:25 in warning
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:12196:6 in warnAboutUpdateOnUnmounted
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:13273:41 in scheduleWorkImpl
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:6224:19 in enqueueSetState
- node_modules/react/cjs/react.development.js:242:31 in setState
* null:null in componentWillMount$
- node_modules/regenerator-runtime/runtime.js:62:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:296:30 in invoke
- ... 13 more stack frames from framework internals
constructor() {
super();
this.state = {
userPhoneNumber: "",
};
}
async componentWillMount() {
await firebase.database().ref('/Users/' + firebase.auth().currentUser.uid).on('value', async snap => {
if (snap) {
await this._setPhone(snap.val())
} else {
this.props.navigation.navigate('Phone')
}
});
console.log(this.state.userPhoneNumber);
}
_setPhone = (snap) => {
const val = parseInt(snap, 10);
this.setState({
userPhoneNumber: val
})
};
If you are sure that you are receiving the correct value for snap. Then the issue that you have is that setState is asynchronous. That means it takes time for state to set.
Unfortunately they way you are checking your state to see if the value has been set is wrong.
You should use a callback in the setState function, so your setState would become:
this.setState({userPhoneNumber: val}. () => console.log(this.state.userPhoneNumber));
I would recommend taking a read of the following articles by Michael Chan that go into more detail about setting state
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
There are also a few issues with your use of async/await and promises it looks like you are mixing the syntax between them. You either use one or the other, not both. This article goes into detail about the differences between them.
this.setState does not return a promise so using await this.setState does nothing.
This is how I would refactor your code:
componentDidMount() { // componentWillMount is deprecated
// you are using a promise to access firebase so you shouldn't be using `async/await`
firebase.database().ref('/Users/' + firebase.auth().currentUser.uid).on('value', snap => {
if (snap) {
this._setPhone(snap.val()) // remove the await as it is not doing anything
} else {
this.props.navigation.navigate('Phone')
}
});
}
_setPhone = (snap) => {
const val = parseInt(snap, 10);
this.setState({ userPhoneNumber: val}, () => console.log(this.state.userPhoneNumber)) // include the callback to check the value of state
};
Updated question
You must be calling setState when the component has been unmounted. You need to check to make sure that your component is mounted before calling setState.
One way of doing it is by having a boolean flag that monitors when the component is mounted.
componentDidMount () {
this._isMounted = true;
}
componentWillMount () {
this._isMounted = false;
}
when you set your state you can do something like this
if (this._isMounted) {
this.setState({key: value});
}
You can see more about it here https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
Just set a _isMounted property to true in componentDidMount and set
it to false in componentWillUnmount, and use this variable to check
your component’s status
This it not an ideal solution but it is the simplest, as you really should be cancelling your promises etc, so that setState is never called as the promise has been cancelled.
I have a function that returns json:
const mapDispatchToProps = dispatch => {
return {
articleDetail: (id) => {
return dispatch(articles.articleDetail(id));
}
}
};
I get the result of the call here:
class ArticleDetail extends Component {
constructor(props) {
super(props);
this.state = {
articleId: props.match.params.id,
asd: "",
art:{}
};
}
componentWillMount() {
this.props.articleDetail(this.state.articleId).then((res) => {
console.log(res.article);
this.setState({art:res.article})
});
this.setState({asd: "asda"})
}
console.log(res.article) return me: {id: 1, author: {…}, headline: "First test article", description: "sadasdsads", img_name: "D.png", …}
but I can't write this result in state, just outside the function, as I did with asd.
I would appreciate it if you would help me, maybe there is some way to write the result of this.props.articleDetail () in state.
I also wanted to ask if I could write the result of calling this function into a variable, and the function returns promise
And also, is it possible to set some variable over this function and record what my console.log "returns" to my external variable.
Thank you so much for your time.
how did you check if the state changed?
In order to properly check if the state has been updated apply a callback to the setState function like this (remember that setState is async):
this.setState({ art: res.article }, () => {
// this happens after the state has been updated
console.log(this.state.art);
});
in regards to your comment about setting the state in the lifecycle methid then it's perfectly fine as long as you do it in componentWillMount and not in componentDidMount.
This is how my state looks like:
constructor(props, context) {
super(props, context);
this.state = {
show: false,
btnLabel: 'GO!',
car: {
owner: false,
manufacturer: false,
color: false
}
};
}
and this is how I modify state:
handleClickFetchPrice() {
this.setState({btnLabel: 'Fetching data...' });
console.log(this.state.fetchPriceBtn);
const url = 'some url';
axios.get(url)
.then(res => {
let car = [...this.state.car];
car.owner = res.data.owner;
car.manufacturer = res.data.manufacturer;
car.color = res.data.color;
this.setState({car});
})
}
The attribute car is updated, but fetchPriceBtn is not - the output of console.log(this.state.fetchPriceBtn); is still GO!.
What am I overlooking? Why the fetchPriceBtn is not updated?
React setState is an asynchronous process - you don't know exactly when it will be updated, you can only schedule the update.
To achieve your desired functionality, you can provide a callback into the setState method.
this.setState({ btnLabel: 'Fetching data...' }, () => console.log(this.state.fetchPriceBtn))
You can learn more following the documentation on the method.
#christopher is right, setState is an asynchronous process. But when second time call handleClickFetchPrice() function your btnLabel is value will be equal to Fetching data...
As answered in previous answers setState is asynchronous, so your console.log can't catch up the state change immediately. Again as suggested you can use callback function to track this change but if you use console.log just for debugging or want to see what changes in your state you can do this in your render function. And using a callback just for debug is not a nice way. Its purpose somehow different and if you check the official documentation, componentDidMount method is being suggested for such logic.
render() {
console.log( this.state.foo );
return (...)
}
If you do that you see two console.log output, one before state change and one after.
Also, your state operations might be enhanced. You car property is not an array, but you are converting it to an array and setting it? Is this what you intend:
axios.get(url)
.then(res => {
const { owner, manufacturer, color } = res.data;
this.setState( prevState => ( { car: { ...prevState.car, owner, manufacturer, color } } ) );
})
Here we are not mutating our state directly, instead we are using spread operator and setting the desired properties. For your example we are setting the whole property actually.
One last note, I think you want to do that something like that:
this.setState( { btnLabel: "fetching } );
axios.get(url)
.then(res => {
const { owner, manufacturer, color } = res.data;
this.setState( prevState => ( { car: { ...prevState.car, owner, manufacturer, color }, btnLabel: "go" } ) );
})
If your intention is somehow to do a status change/check this might no be a good logic as you have seen setState is not synchronous. Do this carefully.
I want to know why when I dispatch action before my console log prints old state.
if I do next:
reducer.js
let initialState = { display: false };
const MyReducer = (state = initialState,action) => {
...
case 'SET_DISPLAY':
return { update(state,{ display : {$set: action.display } }) }
break;
default:
return state;
break;
}
ActionCreator.js
let ActionCreator = {
setDisplay(value) {
return(dispatch,getState) {
dispatch({ type: 'SET_DISPLAY',display: value})
}
}
};
app.js
componentDidMount(){
this.props.dispatch(ActionCreator.setDisplay(true))
// expected : true
console.log(this.props.display)
// prints : false.
}
const mapStateToProps = (state) => {
display : state.display
}
but I can see changes in my redux dev-tools console.
PD I use redux-thunk as Middleware.its just example,all my code seems good and works great,but,its a question.
Why console logs old state instead a new state (its ilogic, if I dispatched an action before call logs) I will apreciate your answers,thanks.
This is because you are using redux-thunk and your dispatch happens aynchronously.
this.props.dispatch(ActionCreator.setDisplay(true)) will not set display true immediately.
Since you are not making a network request or anything async in that action why dont you change the action creator to
let ActionCreator = {
setDisplay(value) {
return { type: 'SET_DISPLAY',display: value};
}
};
Now it will happen synchronously. Also dont put console log immediately after dispatching. As redux updates state, old state is not modified. Instead it creates a new state instance with updated value. This new value will be passed as props to your component via connect of react-redux.
Try printing display in render() method, you will see that it is called twice and second one will display true.
First, I would recommend not to rely on the fact that dispatching an action may be synchronous; design as if everything was asynchronous. When eventually you dispatch an async actions, you will be pleased to have your mindset ready for that.
Second, your action creator return a function (you must be using the thunk middleware), which is why you get this behaviour.
componentDidMount(){
startSomethingAsync();
}
componentDidUpdate(){
if (!this.props.asyncCompleted) return;
if(this.props.asyncResultFn) {
this.props.dispatch({ type: ... value: VALUE_CONDITIONAL_TRUE})
}
else{
this.props.dispatch({ type: ... value: VALUE_CONDITIONAL_FALSE})
}
}