zedArt
zedArt

Reputation: 487

fetch the text of my application from the server

I want to change all the static text in my app with a text from a server so I have to fetch this text in LoadingScreen and then export it to use it in other screens

<Text>My products</Text> to <Text>{constants.myProduct}</Text> after import constant from LoadingScreen

How to export the json response from LoadingScreen to all the other Screen ? there is another approach ? PS. I don't use Redux

Upvotes: 0

Views: 26

Answers (1)

Batraz Jioty
Batraz Jioty

Reputation: 306

The simplest way, but not the best, is just create and export variable with all text keys. For example:

// text.utils.js 
let _textData;

export const loadTextData = () => fetch(YOUR_SERVER)
 .then((r) => r.json())
 .then(r => _textData = r);

export const getTextData = (key, defaultValue) => _textData[key] || defaultValue;

// init inside App or something else
import {loadTextData} from 'text.utils.js';

componentDidMount() {
  loadTextData();
}

// inside components
import {getTextData} from 'text.utils.js';

const myProductText = getTextData('myProduct', 'This is product text');
const myProductCountText = getTextData('myProductCount', 'This is product count text');

<Text>{myProductText}</Text>
<Text>{myProductCountText}</Text>

P.S. It's not a good solution for react. The best choice is create a context or hook, that will provide strings to your components. Also if your string object has nested objects, you may reorganise getTextData function

Upvotes: 1

Related Questions