The `useMap()` function consistently returns the value of `{ current: undefined }`

I've been working on a project with react-map-gl. The map itself is rendering fine, but I'm running into an issue with using useMap(). Whenever I try to use it, I always get { current: undefined } in the logs. Any suggestions or solutions?

In my layout.tsx file, here's what I have:

import { MapProvider } from "react-map-gl";
....
<div className="flex h-screen">
  <MapProvider>
    <div>
      {children}
    </div>

    <InternalMap />
  </MapProvider>
</div>

InternalMap.tsx looks like this:

import MapGL, { ScaleControl } from "react-map-gl";

  <MapGL
      ....
   >
    ....some more stuff 

The structure of the children page is as follows:

import { useMap } from "react-map-gl";

const { default: map } = useMap();
console.log(map, useMap())

Answer №1

Having made errors in my monorepo, I mistakenly imported react-map-gl from an incorrect location with a version mismatch.

Answer №2

Make sure you have the necessary API access token for Mapbox GL.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import ReactMapboxGl, { GeoJSONLayer } from "react-mapbox-gl";
import * as turf from "@turf/turf";
import geojsonStyles from "./geojsonStyles";
import "@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css";

import "./styles.css";

const Map = ReactMapboxGl({
  accessToken:"enter your access token"
});

class App extends Component {
  onDrawCreate = ({ features }) => {
    console.log(features);
  };

  onDrawUpdate = ({ features }) => {
    console.log({ features });
  };

  render() {
    const centerPoint = [-73.975547, 40.691785];

    var radius = 0.1;

    var options = {
      steps: 50,
      units: "miles",
      properties: {
        text: "test"
      }
    };

    const firstCircle = turf.circle(centerPoint, radius, options);

    const secondCircle = turf.circle(centerPoint, radius * 2, options);

    const thirdCircle = turf.circle(centerPoint, radius * 4, options);

    return (
      <div className="App">
        <Map
          style="mapbox://styles/mapbox/streets-v9" // eslint-disable-line
          containerStyle={{
            height: "100vh",
            width: "100vw"
          }}
          zoom={[14]}
          center={[-73.975547, 40.691785]}
        >
          <GeoJSONLayer {...geojsonStyles} data={firstCircle} />
          <GeoJSONLayer {...geojsonStyles} data={secondCircle} />
          <GeoJSONLayer {...geojsonStyles} data={thirdCircle} />
        </Map>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Access the CodeSandbox URL here:

https://codesandbox.io/p/sandbox/react-mapbox-gl-turf-mueyi?file=%2Fsrc%2Findex.js%3A1%2C1-65%2C1

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The useEffect hook is executed only once and will not fetch data again upon refreshing the page

There's this component in my project that fetches data from a website and attempts to extract its keys. The issue I'm facing is that it functions correctly the first time, but upon refreshing the page or saving the project in VSCode (which trig ...

What is the best method to eliminate whitespace in mobile view when utilizing the <Image /> tag in Next.js?

I am currently developing a website using Next.js. I have used the <Image /> tag to display images on the site. On mobile view, I noticed some white space around the image components, while on desktop everything looks fine. Upon checking the network ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

Challenges with Apollo GraphQL: Struggling to get the GraphQLWsLink (Subscriptions) to work with Next.js due to issues with the WebSocket implementation

Recently, I set up a GraphQL server in Go by following a tutorial closely. My front-end is developed using Next.js and I'm currently working on creating a client to connect to the server. Despite referring to the subscription docs thoroughly, I can&ap ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Material-UI: Eliminating linkOperator functionality in data-grid

Is there a way to completely eliminate the linkOperator UI from the filter panel? I managed to move pagination to the top of the table using Material-UI, but can I achieve the same for the "Operators" menu programmatically? ".MuiDataGridFilterForm-linkOpe ...

Tips for improving performance in React by utilizing callback functions to eliminate lag when using setState

How can I improve performance in setState by using a callback function in React? I attempted to use a callback but the state is still lagging and I am unable to map the data in the array state. improvePerformance(){ ServerAddr.get(`/dis ...

Tips on handling multiple Redux toolkit CreateApi interceptors

I came across this solution here for implementing a reAuth baseQuery in Redux Toolkit. I have several backend services that all use the same refresh token concept. Is there a way to create a single baseQueryAuth function that can be used by multiple creat ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Dropdown select utilized to modify the value in MUI Datetimepicker

Currently, I am facing an issue with the react datetimepicker where the value does not change when selecting an option (for example: choosing 6 months should update the finish date to reflect this selection). Below is the code snippet: Child Component c ...

You are unable to update the state while using fetch, even with the arrow function

As a newcomer to react, I recently delved into using the fetch API to retrieve population data from an external source. Despite successfully pulling the data, I encountered an issue where updating the state within the fetch block did not result in the ch ...

Transferring information from the front end to the backend route in React applications

I am new to using React and express, and I need to send data that I have collected from a form. The data I want to send back is the user's email stored in the state. However, I'm unsure of how to make this request. class ForgotPassword extends C ...

Tips for catching errors in Apollo Client while executing GraphQL queries

Here is my approach to querying data from a Graphql engine. export GraphQLWrap <TData, TParam = {}>({ query, extractData, children, queryVariables, skip, }: AsyncWrapProps<TData, TParam>) => { return ( <ApolloConsumer> ...

Compiling React Native in Node.JS encountered a critical error

I'm in the process of putting together a react native guide for creating forms, which can be accessed here: - https://github.com/smhatre59/cloudstorage However, when I try to compile using "npm run-script build" or even for development using "npm sta ...

Can Next.js 13 support the usage of axios?

Despite trying to implement the SSG operation with the fetch option {cache: 'force-cache'}, I consistently received the same data even when the mock server's data changed. I found that using the fetch option {cache: 'no-store'} do ...

Is it possible to reposition a label in Material-UI?

Currently, I am utilizing Material UI for react and I am looking to shift the position of the label within text fields to the right. However, due to its motion, it does not appear as visually appealing. Is there a way to modify this while maintaining the ...

"Enhancing User Experience: Implementing Internationalization and Nested Layouts in Next.js 13.x

In the midst of working on a cutting-edge Next.js 13 project that utilizes the new /app folder routing, I am delving into the realm of setting up internationalization. Within my project's structure, it is organized as follows: https://i.stack.imgur.c ...

How can I fix the error saying "prop-types not detected on request"?

I'm embarking on a fresh ReactJS project utilizing material-ui Next along with fuse-box. All necessary dependencies have been successfully installed: "dependencies": { "material-ui": "^1.0.0-beta.27", "material-ui-icons": "^1.0.0-beta.17", ...

Is there a method to consistently keep the horizontal scrollbar in view for the MUI Data Grid at all times?

I have a Data table with virtualized columns, totaling more than 25 in number. Users can easily scroll horizontally using a trackpad, but without one, they may struggle to access all the columns due to the delayed appearance of the scrollbar. Is there a w ...

The useCallback hooks persist outdated values when the list is refreshed

Why am I not getting the expected values every time the function onRefresh is called using Hooks? Example when onRefresh is called twice: Expected values: true 0 20 false true 0 20 false Received values: false 0 0 false false 20 20 false Initial st ...