Can you please explain how I can retrieve information from a Firebase collection using the NextJs API, Firebase Firestore, axios, and TypeScript?

I'm currently utilizing api routes within NextJS 13 to retrieve data from Firebase. The code for this can be found in api/locations.tsx:

import { db } from "../../firebase";
import { collection, getDocs } from "firebase/firestore";
import type { NextApiRequest, NextApiResponse } from "next";

const Locations = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    const locationsSnapshot = await getDocs(collection(db, "locations"));
    const locationsData = locationsSnapshot.docs.map((doc) => ({
      ...doc.data(),
      id: doc.id,
    }));

    res.status(200).json({ locationsData });
  } catch {
    res.status(400).end();
  }
};

export default Locations;

Next, I have a component called Locations.tsx. In this component, I am attempting to save the locations retrieved into the locations state object like so:

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Container,
  Content,
  Main,
  StyledLink,
  Title,
} from "../components/sharedstyles";
import axios from "axios";

export type LocationData = {
  film: string;
  imdbId: string;
  location?: string;
  scene?: string;
  coords: [number, number];
}[];

type GetLocationResponse = { data: { locationsData: LocationData[] } };

export default function About() {
  const [locations, setLocations] = useState([]);

  const getLocations = async () => {
    // Fetch locations data from locations endpoint and return location data
    const res = await axios.get<GetLocationResponse>("/api/locations");

    return res.data.locationsData;
  };

  useEffect(() => {
    setLocations(getLocations());
  }, []);

  return (
    <Container>
      <Main>
        <Title>Locations</Title>
        <Content>
          <ul>
            {locations?.map(({ location }) => (
              <li>{location}</li>
            ))}
          </ul>
        </Content>
        <Link href="/" passHref legacyBehavior>
          <StyledLink>&larr; Home</StyledLink>
        </Link>
      </Main>
    </Container>
  );
}

However, an error is occurring stating

Property 'locationsData' does not exist on type 'GetLocationResponse'.
, despite my attempt to add "locationsData" to the type definition
type GetLocationResponse = { data: { locationsData: LocationData[] } };

If anyone could provide insight as to why this error is happening and how it can be resolved, I would greatly appreciate it. Thank you!

Answer №1

Your frontend application requires a response object containing a data property:

type GetLocationResponse = { data: { locationsData: LocationData[] } };

However, your backend is currently sending an object with only the property locationsData:

res.status(200).json({ locationsData });

It may be beneficial to adjust the frontend's expectations to align with what the backend is providing by removing the data property:

type GetLocationResponse = { locationsData: LocationData[] };

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

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Teaching sessions along with the implementation of functions

I've created a set of input fields with the class replaceInput. The idea is to have a simple function that clears the value when the user focuses on the field, and then returns it to 'X' if the field is empty on focus out. My query is, coul ...

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

Setting the Node environment as an environment variable within the application: a step-by-step guide

Struggling with setting process.env.NODE_ENV to TEST in my code. Check out the relevant snippets below: test.js import server from "../../src/index.js"; process.env.NODE_ENV = "test"; console.log(process.env.NODE_ENV); // outputs &qu ...

Array of generic types in Typescript

Here's a method that I have: getFiveObjectsFromArray(array: T[]) { return array.slice(0, 5); } I've been using this method multiple times. Is there a way in TypeScript to pass a generic argument instead of using multiple types? Also, when ...

Is there a way to invoke a function in an iframe from its parent?

How can I call a function that is in an iframe from the parent document? If the function were in the parent, I could simply use parent.func(); but since it's within the iframe, how can I still call it successfully? JavaScript keeps saying it can' ...

Discover how to set up lazy loaded child routes within a parent route that is also loaded lazily in Angular 2

Struggling to implement lazy loading for my app has been a series of challenges. I successfully implemented lazy loading for the main route, /admin, but now I am facing issues while adding another route, /admin/login. This is what I tried: admin-router.m ...

Error message: Unable to retrieve `__WEBPACK_DEFAULT_EXPORT__` before initializing Firebase Admin in a nx and nextjs application

My current project involves a Typescript Nx + Next.js App integrated with Firebase (including Firebase Admin). In this codebase, I have defined a firebase admin util as shown below - // File ./utils/FirebaseAdmin.ts // import checkConfig from './check ...

Infuse the theme into the sx prop of MUI 5

The code snippet above was originally written using MUI v4: const useStyles = makeStyles(theme => ({ toolbarMargin: { ...theme.mixins.toolbar } })) To update this code to MUI v5 and utilize the sx prop, I attempted the following implementation: ...

Using input masking to restrict user input to only numbers and English alphabet characters

My input field is masked as "999999999" and functions correctly with an English keyboard. However, I am able to enter Japanese/Chinese characters into it, which breaks the masking. Is there a way to limit input to English keyboard numerics only? <inpu ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

Is it possible to utilize the existing class elements as an array identifier?

Can you leverage a string from an element's CSS class as an array name? I am searching for a more efficient way to store default animations that may expand gradually to encompass more options in the array. Example JavaScript (jQuery): - var col ...

What makes FC function components stand out from traditional vanilla React function components?

I recently came across this FC function component: const LabelForm: FC<LabelFormProps> = ({ labels, selectedID, }) => { const selectedLabel = selectedID !== undefined && labels[selectedID]; In my usual implementation, I do it like t ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Disable page scrolling after making changes to the DOM

When my JavaScript function executes on page load and at set intervals, it cycles through images supplied by another PHP script. However, every time the function manipulates the DOM, the page scrolls back to the top of the containing div, which is quite fr ...

The CSS file is failing to recognize the changes made to the data-theme attribute in the HTML

Currently implementing a dark theme on my website involves adding a toggle switch to the footer.html page, which adds a variable named data-theme = 'dark' to the html. The scss files of the footer and core are adjusting accordingly based on the c ...

Encountering an issue with Angular build in Docker: [ERR_STREAM_DESTROYED] - Write function cannot be called after a stream

Below is the docker file I'm using to build my Angular project: FROM node:12-buster-slim as build-step RUN mkdir -p /app COPY . /app WORKDIR /app RUN chmod 777 -R /app RUN npm install ARG configuration=production RUN npm run build -- --output-path=./ ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Exploring the Scope of LocalStorage in Javascript

I've recently begun working with local storage and encountered some scope issues. Whenever I try to console.log(test), the second if statement returns undefined. What am I missing here? This is my current code; $("document").ready(function(){ ...