Doubt Fetch + React Native

Asked

Viewed 54 times

1

beauty? I am developing an App with Expo for a client, but when I consult (via barcode) its API, always the first time returns an empty Array, if I do the query then the data is returned. Can you tell me why? This app reads barcode, so I created a reader component and it returns the code and reads from the API

I tried to check the syntax of the functions, switch to async, remove async, etc and nothing solves. Remains the same

Follows the code

const [data, setData] = useState('');
const [produto, setProduto] = useState([]);

const onCodeScanned = (data) => {
    setData(data);
    
    fetch(`http://xxx.xxx.xxx.xxx:8090/rest/COLETPRC?codbarras=${data}`)
    .then((response)=>response.json())
    .then((json)=>{
        setProduto(json.produtos[0]);
        console.log(produto); 
    })
    .catch((error) => {
        console.error(error);
    });
    setModalVisible(false);
};

Could you tell me why this is happening? Follow a screen with what occurs

Console.log

  • You tried to use async/await where? In function onCodeScanned? You know that setProduto is soon signed console.log(produto); will only show the value passed and not updated by setProduto.

  • Good morning. Solved by "shortening" the path. That way I removed the useState Products and passed straight back to the console.log(). I changed the line setProduto(json.produtos[0]); console.log(produto); for only console.log(json.produtos[0]);

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.