Paddy
Paddy

Reputation: 803

React JS, load json data then manipulate it

Started to play around with react, just learning the small syntax stuff at the moment, im stuck on AJAX requests with data displaying.

The console gives me an error saying the local version of test.json cannot be found. It is in the same directory as the header.js file

//header.js
import React from 'react';
import $ from 'jquery'; 

var theData = [];

var Header = React.createClass({
    getInitialState: function() {
        return {
        data: null
        };
    },
    componentDidMount: function() {
        $.ajax({
            dataType: 'json',
            url:  "./test.json",
            success: function(data) {
            theData.push(data);
            console.log(theData);
            }
        });
    },
    render: function() {
        return (
        <div>
            <div id="theData" className="theData"></div>
              {theData.someValue}
            </div>
        </div>
        );
    }
});

Upvotes: 0

Views: 875

Answers (1)

user5224313
user5224313

Reputation:

test.json might be in the same directory as header.js, but your code is running client-side and the client (browser) has no idea of what test.json is.

Instead, you should define an endpoint in your server-side logic to read the contents of test.json and return it back to the client as a JSON object. In your client-side logic, the URL property in your current XHR should be replaced with the URI to the endpoint.

Side note: your component as-is won't display any data after the XHR is complete. theData will be properly mutated but it won't trigger a component rerender. You should instead associate your XHR response JSON with component state (which you initialized properly in getInitialState), and React will rerender accordingly when its value is modified.

Update with a code example, assuming your server is Express.

On the server:

const fs = require('fs');
const app = ...

app.get('/name-this-endpoint-appropriately', (req, res) => {
    const json = fs.readFileSync('test.json', 'utf8');
    res.send(json);
});

On the client (with fixes as mentioned in the side note above):

import React from 'react';
import $ from 'jquery'; 

var Header = React.createClass({
    getInitialState: function() {
        return {
            data: []
        };
    },
    componentDidMount: function() {
        $.ajax({
            dataType: 'json',
            url:  "/name-this-endpoint-appropriately",
            success: (data) => this.setState({data})
        });
    },
    render: function() {
        return (
        <div>
            <div id="theData" className="theData"></div>
              {this.state.data.someValue}
            </div>
        </div>
        );
    }
});

Upvotes: 2

Related Questions