I have a variable I'm setting based on the result of an async function, the variable is initialState
const initialState = await getContacts()
.then((body) => {
console.log('body: ');
console.log(body);
return body;
}).catch(err => console.log(err));
My getContacts() returns a promise that should be the result of this function:
export async function getContacts() {
let data = fetch('/api/contacts').then((data) => {
console.log(data);
return data.json();
}).catch(err => console.log(err));
return data;
}
I think part of my problem might be that I'm trying to call this from a plain javascript file. It is actually the index.js of my React application. I'm fetching some sort of initial state of my app from the DB before I load up the app. I should move this code and clean it up quite a bit, but I was trying to get a quick and dirty test up and running. I'm getting a compiler error:
SyntaxError: \contacts\client\index.js: Can not use keyword 'await' outside an async function
My index.js that contains the await is this:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
import { composeWithDevTools } from 'redux-devtools-extension';
import { getContacts } from './server/api';
const initialState = await getContacts()
.then((body) => {
console.log('body: ');
console.log(body);
return body;
}).catch(err => console.log(err));
console.log('initial state: ');
console.log(initialState);
const composeEnhancers = composeWithDevTools({});
ReactDOM.render(
<Provider store={ createStore(reducers, initialState, composeEnhancers(
)) }>
<App />
</Provider>
, document.querySelector('.container'));