0

Im trying to console log a certain field in my react app. I'm trying to log a certain columns from the table. The table itself looks like this: Table screenshot

I'm trying to console log the listingTitle column for a selected oid as we can see from the code.

Here is my code:

const [item, setItem]= useState([]);
const fetchItem= async ()=>{
    const fetchItem= await fetch (`http://link to server/items?oid=${match.params.oid}`
    );
    const item= await fetchItem.json();
    setItem(item.rows[0])
    console.log(item.listingTitle)
    

The console log logs "undefined" and im not sure why it does that.

Thank you for your help in advance!

When i console.log(item) on its own this is what fetch returns: fetch return of console.log(item)

When i tried the code below:

useEffect(() => {
  console.log(item)
}, [item])
toast.configure()

This was the returned value; This was the returned value;

Jakub
  • 21
  • 4
  • 1
    `setItem` is asynchronous and does not occur immediately, but also you have 2 different things called `item` here so it is difficult to know which you are trying to log – WebbH Apr 21 '22 at 13:54
  • Have you checked what `fetch()` actually returns and can you please provide a sample of that data? You might wanna check the HTTP status code using `fetchItem.status`. – Mushroomator Apr 21 '22 at 13:55
  • @Mushroomator I edited the question to include a screenshot of what data i get after i console.log(item) on its own – Jakub Apr 21 '22 at 14:00
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Brian Thompson Apr 21 '22 at 14:10

1 Answers1

0

use useEffect to see the changed state: if the item still empty array, then your fetch result is not correct.

useEffect(() => {
    console.log(item)
}, [item])

after edit: you are setting an object to array state, if you want to set all rows:

const [item, setItem] = useState([]) 
setItem([...item.rows])

is ok but if you want to set rows[0] (an object) then you can use like this:

const [item, setItem] = useState(null)
setItem(item.rows[0])
ahmetkilinc
  • 674
  • 7
  • 19