Home > Software engineering >  how to use data after fetch it in js ? i get the data but idk why i cant use it
how to use data after fetch it in js ? i get the data but idk why i cant use it

Time:02-15

i have a small problem that i can't use the data after fetch it from local json file this is screenshots : here the data in the console:

1

here is my code:

fetch('api_link.json')
.then((res) => res.json())
.then((data) => {
    console.log('data:', data);
  })

export const project_info = () => async (dispatch) => {
  try {
    dispatch({ type: PROJECT_INFO_REQUEST });

    var { data } = await axios.get('HERE I WANT TO PUT THE DATA FROM THE JSON FILE');

    dispatch({
      type: PROJECT_INFO_SUCCESS,
      payload: data,
    });

another screenshot to more explain:

can anyone helo me please

#note i am python backend developer :)

this is first time i use react js

CodePudding user response:

Function arguments are scoped to that function, and aren't accessible outside of that function.

What's more: There's no guarantee that the network request will have resolved by the time you call project_info.

Save the promise returned from fetch in a variable, then that promise will be in scope for project_info.

const api_data = fetch('api_link.json')
    .then((res) => res.json())

export const project_info = () => async (dispatch) => {
            try {
                dispatch({
                    type: PROJECT_INFO_REQUEST
                });

                const url = await api_data;

                var {
                    data
                } = await axios.get(url);

                dispatch({
                    type: PROJECT_INFO_SUCCESS,
                    payload: data,
                });

Note that axios and fetch are two APIs for doing the same job. It doesn't really make sense to mix them.

  • Related