0

I have a state variable dataSource that has some data in it.

In a parent component I have the following:

updateFeed = newItem => {
    this.setState({ dataSource: this.state.dataSource.data.unshift(newItem) })
    console.log(this.state.dataSource.data)
  }
  render() {
    console.log(this.state.dataSource.data)
    return (
      <React.Fragment>
        <Header />
        <Route
          path="/"
          exact
          component={props => (
            <Feed {...props} feedData={this.state.dataSource.data} updateFeed={this.updateFeed} />
          )}
        />
        <Route path="/profile/:id" exact component={props => <Profile {...props} />} />
      </React.Fragment>
    )
  }

updateFeed is called from the child component.

onSubmit = () => {
    const newPost = newData // some new data
    this.props.updateFeed(newPost)
  }

The updateFeed function is getting executed on submit, and the console.log is giving the updated data. But inside the render function this.state.dataSource.data is undefined. What am I missing here?

3
  • 1
    Why you are calling unshift? that mutate your state, which should be avoid. Commented Apr 23, 2018 at 20:40
  • I have to insert the element in the front of the array. Commented Apr 23, 2018 at 20:44
  • 2
    then just use spread operator [newItem, ...this.state.dataSource.data] instead. If you mutate your state, your setState would not correctly working. Commented Apr 23, 2018 at 20:47

2 Answers 2

1

You do dataSource: dataSource.data in your setState call, therefore dataSource.data in your render method will actually access dataSource.data.data which is probably undefined. May change updatedFeed to:

 updateFeed = newItem => {
    this.setState(prev => ({
       dataSource: {
           ...prev.dataSource,
           data: prev.dataSource.data.concat(newItem)
       }
    }));      
  }

Which ensures a pure state.

Sign up to request clarification or add additional context in comments.

Comments

1

It is because previously, this.state.dataSource is an object having key data. So even you are setting new value in updateFeed but in the very next line, state has not been updated yet. React does this asynchronously. so your log statement is showing old data.

You need to update state like this

const dataSource = this.state.dataSource;
dataSource.data.unshift(newItem);
this.setState({ dataSource: dataSource })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.