How do I make this asynchronous query synchronous in JavaScript?

Viewed 9485

I am having a problem where my Administrator page is rendering without checking whether the current user has permission to view that page. Once it checks permissions (takes a second or so) and realises a user doesn't have permissions an error page occurs. I would ideally not like it to render at all until it checks permissions. I think the problem is that the query to get the current user's data is asynchronous and so I believe I need to use async and await to make it synchronous.

This is a AdministratorPage.jsx file that shouldn't render whilst permissions are checked

import currentUser from '../lib/currentUser';
import React, { Component } from 'react';
import { ApolloConsumer } from 'react-apollo';

class AdministratorPage extends Component {

    render() {
        return (
            <ApolloConsumer>
                {(client) => {
                currentUser(client).then((data) => {
                    if(!data.currentUser..permissions)) {
                        this.props.history.push('/error');
                    }
                    return (
                       ... content rendered ...

The execution of code calls the second return function before it completes the currentUser(client).then((data) => call but I would like this call to be completed first.

This is the currentUser.js file that executes the query to check the current user's data

import gql from 'graphql-tag';

export default apolloClient => apolloClient
    .query({
        query: gql`
            query CURRENT_USER {
                name
                age
                gender
                permissions
            }
        `,
    })
    .then(({ data }) => ({ currentUser: data }))
    .catch(() =>
        ({ currentUser: {} }));

I think I need to transform the query from currentUser.js into a synchronous function using async and await. Does anyone know how to do this?

2 Answers

You can take advantage of async/await

import gql from 'graphql-tag';

const request = apolloClient => apolloClient
    .query({
        query: gql`
            query CURRENT_USER {
                name
                age
                gender
                permissions
            }
        `,
    })

async getUser = () => {
   const response = await request(apolloclient);
   console.log(await response);
}
Related