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

1
  • 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 Commented Aug 10, 2021 at 18:12

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.