Created on 23 March 2023, over 1 year ago
Updated 24 March 2023, over 1 year ago

Problem/Motivation

As a Drupal/PHP developer with some basic knowledge of JavaScript and TypeScript, I'd like to use drupal_state for my NextJS project using Typescript. When I'm trying to follow the documentation and use const recipesFromApi = await store.getObject({ objectName: 'node--recipe' }); to get a list of nodes I don't know what to do next. I'm trying to run the map method on this constant but I got an error.

Steps to reproduce

Create a NextJS 13.x application with TypeScript with the following file in /app directory:

#/app/page.tsx
import Link from "next/link";
import { DrupalState } from '@gdwc/drupal-state';

export default async function Recipies() {

  const store = new DrupalState({
    apiBase: 'https://dev-ds-demo.pantheonsite.io',
  });

  const recipesFromApi = await drupal.getObject({ objectName: 'node--recipe' });

  return (
    <>
      <h1>Recipies</h1>

      {recipesFromApi.map((item) => {
        return (
          <li key={item.id}><Link href={`recipies/${item.id}`}>{item.title}</Link></li>
        )
      })}
    </>
  )
}

Linter will throw following error:

info - Linting and checking validity of types ...Failed to compile.

./app/page.tsx:11:23
Type error: Property 'map' does not exist on type 'void | PartialState

'. Property 'map' does not exist on type 'void'. 9 | Recipies 10 | > 11 | {recipesFromApi.map((item) => { | ^ 12 | return ( 13 |
  • {item.title}
  • 14 | )

    Proposed resolution

    Please describe how to manipulate data using the Drupal State library.
    πŸ’¬ Support request
    Status

    Closed: duplicate

    Component

    Documentation

    Created by

    πŸ‡΅πŸ‡±Poland Marcin Maruszewski

    Live updates comments and jobs are added and updated live.
    • Needs documentation

      A documentation change is requested elsewhere. For Drupal core (and possibly other projects), once the change has been committed, this status should be recorded in a change record node.

    Sign in to follow issues

    Comments & Activities

    • Issue created by @Marcin Maruszewski
    • Status changed to Closed: duplicate over 1 year ago
    • Hi @Marcin β†’ . We are aware that the types returned from DrupalState could be refined. In the meantime, you can use Type Assertions to tell the TypeScript compiler which type you are expecting this data to be.

      For example:

        const recipesFromApi = (await store.getObject({
          objectName: "node--recipe",
        })) as { id: string; title: string }[];
      

      I am closing this as a duplicate of #3321306 β†’ . Feel free to discuss any proposed ideas there.

    Production build 0.69.0 2024