-1

I have made a component with 2 column section . left one is form and right one show all posts from db. after submitting form new inserted data doesn't show in right section unless I refresh, can anybody help? tkx

Mehdi Yaghoubi
  • 561
  • 3
  • 8
  • 24
  • It would be easier to provide solutions if you provided some code, the way you submit your form data and handle the response in your component would be good for example. – Peppermintology Jul 18 '19 at 12:02

2 Answers2

1

You need to use componentWillReceiveProps(nextProps) in your component and set your posts state in componentWillReceiveProps and automatically your component will re-render.

For example:

import React from 'react';

class Post extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.posts) {
      this.setState({ posts: nextProps.posts });
    }
  }

  render() {
    return (
      <div>
        {this.state.posts.map((post, index) => (
          <p>{post.title}</p>
        ))}
      </div>
    );
  }
}
const mapStateToProps = state => ({
  posts: state.posts,
});

export default Post;

Note: This will work if your React version is less than 17

componentDidUpdate will work if you are using most latest version of react. Here is the comparison

NN796
  • 1,247
  • 11
  • 31
  • I use useEffect(), data are show in console after submit but not in page unless I refresh the page. – Mehdi Yaghoubi Jul 18 '19 at 13:12
  • @MehdiYaghoubi is this your own custom function `useEffect()`? Please update your answer and provide some code for further debugging. – NN796 Jul 18 '19 at 13:19
0

This is easy, after storing into db, make request from db/api get all relevant records and show all the lists, and update state of component.

SamiMalik
  • 160
  • 2
  • 15