Reputation: 199
I would like to read the data from customData.json, through the code below but here it requires a url, although i would like to read it locally instead, is it possible to do this?
var customData = require('./customData.json');
export function fetchQuestions() {
return dispatch => {
fetch(customData, {
method: 'get',
headers: {
'Accept': 'application/json',
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
}
})
.then(payload => payload.json())
.then(payload => payload.results)
.then(payload =>
dispatch({
type: 'FETCH_QUESTIONS',
payload: payload
})
)
}
}
Upvotes: 1
Views: 542
Reputation: 371233
If you want to read a JSON from localStorage instead of making a network request every time, it's pretty simple, there's nothing async involved. Assuming you've put it into localStorage.customData
:
export function fetchQuestions() {
return dispatch => {
const payload = JSON.parse(localStorage.customData);
dispatch({
type: 'FETCH_QUESTIONS',
payload: payload.results,
});
}
}
Though, unless you're doing something else with it, it would be nicer to save the .results
property only onto the disk, rather than the whole payload, since you're not using the rest of it.
Upvotes: 1