How to correctly write lambda expression in fetch

Viewed 372

I have simple fetch in my react.js project:

export function getUserById(id) {
    const requestOptions = {
        method: 'GET',
        headers: { 'Content-Type': 'application/json','Access-Control-Allow-Origin':'http://localhost:9000' },
        mode: 'no-cors',
    };
    var res = fetch("http://localhost:9000/user/"+id);//there should be a lot of strange lambdas..
    return res;
}

I use this function in other file:

var user = getUserById(userStr);
//some code
//more code

var email=user.mail;
var id = user.id;

Unfortunately - res is always Promise. I don't feel functional programming and react but I need to do it. I know that there should be some lambda expression, but I have no idea how to write them. As you see I need to take email and id from returning JSON. Thanks in advance.

2 Answers

You need to await the fetch call.

See this example on MDN.

export async function getUserById(id) {
    const requestOptions = {
        method: 'GET',
        headers: { 'Content-Type': 'application/json','Access-Control-Allow-Origin':'http://localhost:9000' },
        mode: 'no-cors',
    };
    var res = fetch("http://localhost:9000/user/"+id);//there should be a lot of strange lambdas..
    return res;
}


var user = await getUserById(userStr);
//some code
//more code

var email=user.mail;
var id = user.id;

Edit: You don’t need to await the fetch call, you only need to await getUserById(userStr).

Answer is not that easy. Proper way (await returns promise!) is little bit more problematic. There is my solve ;) :

    return fetch("http://your.fancy.link").then((response) => response.json())

and

function App() {
    const [state, setState] = useContext(MyContext);
    const [loading,setLoading] = useState(true);

    const readUrlParamsFromAuthentication = () => {
        var url_string = window.location.href; //window.location.href
        var url = new URL(url_string);
        var userStr = url.searchParams.get("user-id");
        var userId = null;
        var userEmail = null;
      
        if (userStr) {
            
            getUserById(userStr).then(user=>
                {
                   
                    localStorage.setItem('email', user.email);
                    setState({ email: user.email, isLogged: true });
                    console.log("TUTAAAAJ");
                    console.log(user.email,user.id,state.isLoggedIn);
                    setLoading(false);
                }
            );
            console.log("UserStr");

        }

    }

    useEffect(() => {
        readUrlParamsFromAuthentication();
    }, [])

there should be your return html ;)
Related