Skip to content
Advertisement

How to re-render react-table in .js when data changes in another .js

I am new to react-table and trying to re-render a react-table when data supplied to it changes. Is there anyway to do so? I have tried using useEffect() with no avail.

CLARIFICATION: Usage.js and Updater.js needs to be kept seperated with their functions as shown. I am open to using another approach than global variable if it can help rerender the table when the data value changes.

table.js

JavaScript

globalVariable.js

JavaScript

Usage.js

data is updated by using a GET request in Updater.js and supplied using global variable in globalVariable.js.

JavaScript

Updater.js

JavaScript

A simple explaination with example code would be greatly appreciated.

EDIT #1: Added how data is updated

EDIT #2: After taking the advice of @Obsidianlab and @Johnny, I used Context API using Johnny’s answer (there is an important bug in answer where needs to wrap the .Provider in return(), I am getting the following strange behaviour:

Updater.js

Updated based on @Johnny’s steps

JavaScript

For Usage.js

The following code below works and re-renders:

JavaScript

The following code below does NOT re-render, however console says that the context.data.exactval value is updated.

JavaScript

How can i fix non-render issue related to Context API?

Advertisement

Answer

So, from my understanding, you are updating a global variable created in a js file ./globalVariable.js. I haven’t seen the file, but I believe these variables are outside the scope of what react can “keep an eye on”.

So I suggest you to create a state for your data in the Usage.js, and then update it. Example:

Usage.js

JavaScript

Edit #1

Since you cannot merge both files or export the function, i suggest you tu use ContextAPI

TableDataContext.js

JavaScript

Now you have to wrap your components taht need to consume the TableDataContext with the provider

If you want in your whole app, for example:

JavaScript

This way, you can setData in DummyCall by importing from context:

Updater.js

JavaScript

Finally just import the data from context in your table.js, and you will not need to pass by props

You can learn more about the ContextAPI on React Docs

Hope it works

Advertisement