Home > front end >  json value returned from a promise does not give node values when using React Typescript
json value returned from a promise does not give node values when using React Typescript

Time:10-11

My promise returns the response object that looks like the following:

response:
Person: Array(3)
0: {Name: 'PersonA', Data: Array(2)}
1: {Name: 'PersonB', Data: Array(3)}
2: {Name: 'PersonC', Data: Array(4)}

This is the function used to fetch the response

public getData = (): Promise<any> => {
    
    const personData = `http://url/get/someperson/data/personData.json`;
    return (
      fetch(personData , { method: "GET" })
        .then((response) =>
          response.json().then((response) => ({
            response,
          }))
        )
        .catch((e) => console.log(e))
    );
  };

However, I want to fetch all the Person names and populate them to a drop-down list. However, I'd first just like to fetch all the values of Person name and populate them into a variable.

To do this, if I try something like this val is always undefined

const val = getData().then((personNames: any): void => {
      (personNames.Person);
    });

With my limited understanding, any advice or guidance on resolving this issue is highly appreciated.

Thanks in advance!

CodePudding user response:

Looks like you are getting the function name wrong. It should be getData and not personData.

Also, if you want to return the value assigned to the variable val, you could try:

const val = await getData();

OR if you still want to use then/catch:

let val;
getData().then((personNames: any) =>
  {
    val = personNames.Person; // should assign the value there
  })

CodePudding user response:

I updated your code. You should modify the response and return it.

const val = getData().then((personList: any): [] => {
  return personList.map((person: any) => person.Name);
});

OR one liner expression below

const val = getData().then((personList: any): []=>  personList.map((person: any) => person.Name);
    );
  • Related