Jonny Vaine
Jonny Vaine

Reputation: 13

Making fetch data globally accessible - react

Is there a way of making data brought in by fetch globally accessible to other components in React?

Currently, I have a json file called page.json which has data set out as below:

{
"logo": {
    "src": "images/logo.png"
},
"logout": {
    "text": "Logout"
},
"comingSoon": {
    "title": "There's more to come!",
    "text": "We know it might look a bit bare here right now, but don't worry - we're working on lots of new features coming soon...",
    "points": [
        {
            "id": 1,
            "title": "View documents plus saved quotes and exclusive discounts",
            "text": "You can do all this right now"
        },
        {
            "id": 2,
            "title": "Make simple changes",
            "text": "Change your email address, phone number or marketing permissions - Coming August 2018"
        },
        {
            "id": 3,
            "title": "Make all changes",
            "text": "Add a car, tell us you've moved house, the posibilities are endless - Coming April 2025"
        }
    ]
},
"test": "hello"

}

I'd like my components to be able to access this data, which at the moment is being called in by using fetch():

        class FetchDemo extends React.Component {
        constructor(props) {
            super(props);

            this.state = {
              pageData: []
            };
        }

        componentDidMount() {
            fetch('./page.json').then(res => res.json())
            .then( (result) => {
                this.setState({ 
                    pageData: result
                });
            });
        }

        render(){
            return ( 
                <span>
                {this.state.pageData}
                </span>
            )
        }
    }

I have created a const with some inline arrays in, so I can call these in like <WelcomeMessage name={policies[0].id} /> and this works as I'd hope.

Please let me know if you need me to explain further - first post 'n all!

Upvotes: 0

Views: 2504

Answers (3)

Thananjaya S
Thananjaya S

Reputation: 1689

Yes, you can use those fetched data globally. There are different ways that you can use it.

  1. You can store those fetched data in localStorage or sessionStorage. Both, localStorage and sessionStorage are built in application in web browsers. You can store values in localStorage by

    localStorage.setItem('key', JSON.stringify(data) and you can retrive data from localStorage by JSON.parse(localStorage.getItem('key'));

  2. You can use firebase application for storing your data and using them in any components you need to. Firebase is a database service provided by Google, mainly used as the database for frontend engines such as react,angular and vue.

  3. You can use Redux combined with redux middleware such as redux-thunk. Redux is used for state management. Redux uses store to store your states and it can be accessed in any components you required. The other state management packages are flux architecture by Facebook and mobx.

You can find tutorials for the above-mentioned ways on youtube and e-learning portals. Happy hacking.

Upvotes: 0

Rajat Rastogi
Rajat Rastogi

Reputation: 111

Best way for sharing the data between the component which are not in parent child relationship is by using Redux. Another reason for using redux is that the data flow in redux compliments the data flow of react(as props).

Upvotes: 0

Colin Ricardo
Colin Ricardo

Reputation: 17269

You could have a constants.js file where you export any variables you want to be globally accessible, and then just import those variables wherever you need them.

For example, in constants.js:

export const name = "Colin";

Then in your component file, you can do import { name } from 'constants';.

Note that this is an example of a named export. You can check out this link for more details on exports in JavaScript.

Upvotes: 0

Related Questions