Home > Software design >  How to set state in component remotely on callback?
How to set state in component remotely on callback?

Time:08-11

I am making a react native app which receives data from ws api on callback.
This function resides in api module and look like this:

    ws.onmessage = (e) => { //callbnack to HOME
    const request = JSON.parse(e.data)
    ...
    }

I want to show received text on screen in Component. It has state with text field, and <Text> {this.state.screenText} </Text> element. Both modules imported in Main screen component. How do I do this?

CodePudding user response:

 1. I think you should have to create a custom hook or context provider if you are not calling this API on the Main screen component
 2. If you call this API function on the main screen then you should create a simple function eg. ABC(data) that will receive the data from API and pass it to the function that you are calling as a parameter. On the other side when API gives some responses call this function which you are sending as a parameter and pass the data to it. 

e.g:
 export const sendData = (e, ABC) => { //callbnack to HOME
    const request = JSON.parse(e.data)
    ABC(request)
    ...
    }
    
On Mian Screen :
export {sendData} .....
 function ABC(data){console.log(data)
 }

sendData(e, abc)

CodePudding user response:

Use state management library like redux, zustand, etc. Here's an example with zustand -

store.js

export const useMyStore = create(() => ({
  text: 'hello',
}));

export const setText = (text) => useMyStore.setState({ text });

websocket.js

import { setText } from './store.js';

ws.onmessage = (e) => {
  const request = JSON.parse(e.data)
  setText(request.text);
  ...
}

Main.js

import { useMyStore } from './store.js';

function Main() {
  const text = useMyStore((state) => state.text);
  return (
    <View>
      <Text>{text} </Text>
    </View>
  );
}
  • Related