1

when I am printing console.log(response.data) in console below output is coming.

enter image description here

I created one hook const [result,setResult] = useState([]);

and then output of API I set as

setResult(response.data);

when I am writing below code it is just printing " Data is". it is not printing output of result

              <h1>
                  Data is
               {
                   result.map((res:any)=>{
                       {res.id};
                   })
                }    

              </h1>  

what mistake I am doing?

3
  • 2
    a lot of things can be wrong since you didn't provide enough code segment but from what's given, the map is not properly used. You need to return res.id. Try something like this result.map((res) => res.id) considering the fact you only want id of each element Commented Feb 20, 2022 at 8:09
  • can you supply the full relevant code? Commented Feb 20, 2022 at 8:10
  • thank you araf. I actually want to print all the element. the code you suggested is working for id. but if I open bracked and put res.id; res.name then nothing is getting printted. Commented Feb 20, 2022 at 8:21

1 Answer 1

2

The whole logic of your code it's okay. You are using the useState Hook correctly. And the data your passing to the state is an array which will work fine with the map() method. The only problem I'm seeing is that your map() method is not well implemented.

Try this instead:

<h1>
  Data is
  {
   result.map((res:any)=>{
      return <p>{res.id}</p>
   })
  }    
</h1>  

The map() method always returns something. When it is a one liner it is not necessary to type return.

<h1>
  Data is
  {
   result.map((res:any) => res.id )
  }    
</h1>  

To print multiple properties of the object:

<h1>
  Data is
  {
   result.map((res:any) => {
      return (
        <div key={res.id}>
           <p>{res.id}</p>
           <p>{res.name}</p>
           <p>{res.createdAt}</p>
        </div>
      )
   })
  }    
</h1>  
Sign up to request clarification or add additional context in comments.

7 Comments

actually it is perfectly working. let support along with Id I need to print name so I am writing res=>{res.id ; res.name} then it is not printing anything.
can you suggest how I can print other values like name , createdAt along with id, please.
return <p>{res.id}</p> surely.
I added a new code snippet, try it out.
Great to hear! keep it up
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.