简体   繁体   中英

In reactjs how can I get the response from fetch() in other file

I want to retrieve data from database in server.

In file A I call fetch(url) then I expect to get the response in file B , is this possible?

Back then when I'm using electronJS this can be easily achieved by using ipcRenderer.on('channel', function); .

So in file A I fetch data using ipcRenderer.send('channel', someData); then I received the data in file B by declaring ipcRenderer.on('channel', function(result)); .

Now I am not using electronJS because I plan to build a web app, from what I have learned I can get the data from database using fetch(url) but the problem is I don't know how to receive the data in other file.

let me know if you need more explanation.

ADD EXAMPLE CODE:

I get this example code from here: https://stackoverflow.com/a/48381103/9177853 similar problem but not exactly the same.

In file A :

export const getData = () => fetch("https://api.myjson.com/bins/mp441")
  .then(response => response.json())

In file B :

import { getData } from './path/to/getData.js';

const someFunc = () => {
   getData().then(data => {
       // set redux state
       this.props.setReduxState(data);
   })
}

But file B won't automatically listen to incoming data response thus store the data to redux state, without calling someFunc(); explicitly.

What I want is just by calling fetch(url) on a button click in file A , file B is always ready to listen to incoming response then store the response data to redux store.

What you want is possible, and it sounds like inter component communication, add sample code and hopefully you will get some help. You Component A (File A) to write into a state that Component B (File B) depends on.

Update from your sample code.

  1. If your planning to use Redux: Please take a look at redux action and reducer .It requires some initial setup.

  2. If your app is small I will suggest your look at react hooks useReducer and useState.

  3. You can use the context API in react as well, if your app is relative small and you do not want to pass pros arrount.

  4. And finally you might not need a state management tools at all. I will suggest you create a Root Component and store all your data in its state, and have its child Compoents update and comsume that state. This easily achievable with some reading. You can check one my repo that does it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM