How to get data from local json file using actions and axios.get() (Redux)?
16,349
Solution 1
I meet the similar problem before.I create my react app by create-react-app command.And find that you can only get the static file from the public folder.If you want to the get "db.json",you should put the "db.json" into the public folder.
Solution 2
I know that this question is answered long back. It will help people like me. Instead of using axios or other network libraries you can directly import the json file like below and return it in dispatcher. If you are using local json to test it why do you need network libraries.
import data from './response.json'
export function initializeApp() {
return function (dispatch) {
dispatch({
type: ActionTypes.ActionName,
payload: data
});
}
}
Author by
Jurate
Updated on June 07, 2022Comments
-
Jurate almost 2 years
I wrote Action, should get data from db.json file. But
Error: message "xhr.js:178 GET http://localhost:8083/data/db.json 404 (Not Found)".
Why is it, if my path is correct (db.json is in the same folder)? In profileActions.js:
import axios from "axios"; var customData = require('./db.json'); export function fetchUsers(){ return function(dispatch){ axios.get('./db.json') .then((response) => { dispatch({type:'FETCH_USERS_FULFILLED', payload:response.data}); }) .catch((err) => { dispatch({type:'FETCH_USERS_REJECTED', payload:err}); }) } }
-
user-developer over 6 yearsHave you tried giving absolute path to db.json?
-
user-developer over 6 yearsPlease check github.com/nuxt/nuxt.js/issues/123
-
Abdennour TOUMI over 6 yearsare u using webpack ?
-
theshubhagrwl over 3 yearsThe accepted answer is good. If you need more information then this is a good guide pluralsight.com/guides/…
-