Skip to content
Advertisement

How can I update or re-render a component from another component? (React)

I originally had two components displayed on two different pages via Routes: the RecordList and Create components. It all currently works properly when I use Routes. However, I’m trying to modify this project so that both components are on the same page at the same time instead of being on two different pages.

My goal is to have RecordList update (fetch the data from the server) once I click the “Add Record” button. Currently the Create component is working properly, however I have to refresh the page to see the changes on the RecordList component.

I’m having trouble understanding what I need to do to get RecordList to update when the record is posted to the server. Any guidance is helpful.

Would this be a scenario to use Lifting Up State? I didn’t think so because I believe these two components are sibling components.

Do I need to re-render the RecordList component? Should I just combine these two components into one component? My guess was that it would be better for these to be two separate components.

For reference, I did not write all of this code. I’m trying to modify the project I built using the MERN tutorial on the MongoDB website.

Here is a screenshot of the page: homepage

App.js:

JavaScript

recordList.js:

JavaScript

create.js:

JavaScript

Advertisement

Answer

you have several ways to solve this problem:

  1. you can move records state from recordList to App and pass records to recordList component and pass setRecords to create component as props, so you can update records when statusCode of http://localhost:5000/record/add is 200.

  2. you can use stateManagement packages like redux, redux-toolkit, jotai, … to has a manager to manage changes on the entire application side

  3. you can use context for save records to access records everywhere in the application.

  4. you can use react-query package to manage get and save data together. you can react-query-useful-hooks for optimal and easier use of rickett

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement