Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

javascript - Why im getting an undefined as result with first "onSubmit" but second is ok

Why when I call the "handle Search" function for the first time I get "undefined" but the second time I get my result.

    const handleSearch = (e) => {
    e.preventDefault();
    const proxy = 'https://cors-anywhere.herokuapp.com/';
    const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?';
    const location = `location=${latitude},${longitude}`;
    const radius = '&radius=2000';
    const type = '&keyword=restaurant';
    const key = '&key=xxxxxxxx';
    const SearchUrl = proxy + url + location + radius + type + key;
    console.log(SearchUrl);
    fetch(SearchUrl).then(response => response.json()).then(result => {
        SetList({list: result})
    })
    console.log(list);
}

EDIT: Shouldn't it be alright now? Still undefined for the first time

    const handleSearch = async (e) => {
    e.preventDefault();
    const proxy = 'https://cors-anywhere.herokuapp.com/';
    const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?';
    const location = `location=${latitude},${longitude}`;
    const radius = '&radius=2000';
    const type = '&keyword=restaurant';
    const key = '&key=xxxxxxx';
    const SearchUrl = proxy + url + location + radius + type + key;
    SetList({list: await myRespone(SearchUrl)})
    console.log(list);
}

function myRespone(SearchUrl) {
    console.log(SearchUrl);
    fetch(SearchUrl).then(response => response.json()).then((responseJson)=>{return responseJson});
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put console.log(list) outside handleSearch to get the latest value

const handleSearch = async (e) => {
    e.preventDefault();
    const proxy = 'https://cors-anywhere.herokuapp.com/';
    const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?';
    const location = `location=${latitude},${longitude}`;
    const radius = '&radius=2000';
    const type = '&keyword=restaurant';
    const key = '&key=xxxxxxx';
    const SearchUrl = proxy + url + location + radius + type + key;
    SetList({list: await myRespone(SearchUrl)})
    
}
console.log(list);

The update value of useState is asynchronous, you cannot get the latest value synchronously. Only after the hooks update the value, the component re-render can get the updated value


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...