2

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

Ricardo Sanchez
  • 4,935
  • 11
  • 56
  • 86
  • We can't know what you should pass to the GoogleMap component so... I mean the error is kind of self explanatory, that component expects a number obviously but you pass a function – İlker Aug 10 '21 at 18:12

1 Answers1

1

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);
Aesir9
  • 36
  • 4
  • Thank you very much, it will be great to know if there is a work around to my original, implementation, unfortunately the tutorial I use is a bit dated and I have had no reply to my comments – Ricardo Sanchez Aug 10 '21 at 18:28