Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading