Reputation: 143
I'm making an app that is meant to give me practice using routes, so this is initially using static, local test data. It's in json format already, and it's an object consisting of two arrays (folders and notes). I just want my initial state to be this data. Here's what I tried already:
import React, { Component } from 'react';
import { Route, Link } from 'react-router-dom';
... other imports ...
import store from './dummy-store.js';
class App extends Component {
state = {
folder: [],
notes: []
};
componentDidMount () {
fetch(store)
.then(res => res.json())
.then(folder notes => this.setState({ folder notes }))
}
render() {
....code...
}
}
Upvotes: 1
Views: 2916
Reputation: 202618
If, for example, your JSON file was
{
"folders": [ ... ],
"notes": [ ... ],
...
}
If imported as a local asset within (i.e. bundled with) your app code, access in code
import store from './dummy-store.js';
class App extends Component {
state = {
folder: store.folder,
notes: store.notes,
};
...
If fetched as a public asset external (i.e. in the public folder, somewhere out on the web, etc..) to your app
class App extends Component {
state = {
folder: [],
notes: []
};
componentDidMount () {
fetch("pathToJsonFile")
// return JSON object
.then(res => res.json())
// uses object destructuring of passed parameter
.then(({folder, notes}) => this.setState({ folder, notes }))
}
...
Upvotes: 1
Reputation: 5529
You dont need to fetch because you already imported it, you can pass it as initial state to useState
const [state, setState] = useState(store);
you can check here https://codesandbox.io/s/silly-golick-rshco
Upvotes: 1