Getting InvalidValueError while passing state by useContext

Viewed 30

I setup my context provider like so

import { createContext, useState } from 'react';

export const AppContext = createContext(null);

export default ({ children }) => {
  const [centre, setCentre] = useState({
    lat: 53.719028,
    lng: -2.072784,
  });
  const [radius, setRadius] = useState(2 * 1000);

  const store = {
    radius: [radius, setRadius],
    centre: [centre, setCentre],
  };

  return <AppContext.Provider value={store}>{children}</AppContext.Provider>;
};

And setup my index.js like this

import App from './App';
import AppProvider from './components/utilities/context';

ReactDOM.render(
  <AppProvider>
    <App />
  </AppProvider>,
  document.getElementById('root'),
);

I'm trying to consume the context from a component in App.js so in my Map.js component I have:

import { AppContext } from '../utilities/context';

...

const { radius, centre } = useContext(AppContext);

return (<GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={6}
        center={centre}
        options={options}
        onLoad={(map) => onMapLoad(map)}
      >
      ...
      </GoogleMap>)

If I console.log(centre) from the Map component I get the correct values, the app compiles fine, but the map does not render, and I get this error in the console:

InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number

1 Answers

You are accessing the array [radius, setRadius] with const { radius, centre } = useContext(AppContext);

This is how I usually create my context providers:

import { createContext, useState } from 'react';

export const AppContext = createContext(null);

export default ({ children }) => {
  const [centre, setCentre] = useState({
    lat: 53.719028,
    lng: -2.072784,
  });
  const [radius, setRadius] = useState(2 * 1000);

  const contextValues = { centre, radius };
  const contextFunctions = { setCentre, setRadius };

  return <AppContext.Provider value={{ ...contextValues, ...contextFunctions }}>{children}</AppContext.Provider>;
};

And then you can access these like this:

const { radius, centre, setRadius, setCentre } = useContext(AppContext);
Related