Home > database >  React - how to declare this variable
React - how to declare this variable

Time:03-17

I have this component that pretends to receive an ID of a category of products, make a call to the backend through an API and return the products of this category.

To do this, the first time I render the component I make a default call without optional parameters to the API and return 10 items for example.

But then I have some filters such as the price from, price to or the brand of the product that I collect these values ​​and send them to the API to return a JSON with the products.

For this reason I have created a "handleButtonCLick" function that aims to collect the values ​​of the filters (input box) and make an API call through post.

For this reason I have created a "handleButtonCLick" function that aims to collect the values ​​of the filters (input box) and make an API call through post.

import axios from 'axios'
import GuestLayout from '@/components/Layouts/GuestLayout'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'

const Name = ({ itemsList }) => {
    const router = useRouter()

    //const [itemsList, setItemsList] = useState([])

    const handleButtonCLick = (event, value) => {

        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                category_id: 100,
            }),
        }

        fetch(
            `${process.env.NEXT_PUBLIC_BACKEND_URL}/api/product/category/`,
            requestOptions,
        )
            .then(response => response.json())
            .then(json => setItemsList(json))
    }

    return (
        <GuestLayout>

            <div>
                {itemsList.map((x, i) => (
                      {x.price}€
                ))}
            </div>

            <div className="py-12">
                  <Button  variant="outlined"
                           onClick={handleButtonCLick}>
                           Search items
                  </Button>
            </div>
        </GuestLayout>
    )
}


Name.getInitialProps = async context => {

    let valor = 1;

    const { data } = await axios.post(
        `${process.env.NEXT_PUBLIC_BACKEND_URL}/api/product/category/${valor}/`,
    )

    return { itemsList: data }
}

export default Name

I make the call but I don't know how to set the result obtained to "itemsList", because if I set it this way it tells me that I can't define it AGAIN

const [itemsList, setItemsList] = useState([])

CodePudding user response:

You are trying to declare some React state with the same name as what has already been declared for a prop. Just use a different variable name. Use an useEffect hook to save the passed itemsList prop into state if/when it updates, and update the render to map the local items state.

import axios from 'axios';
import GuestLayout from '@/components/Layouts/GuestLayout';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

const Name = ({ itemsList }) => {
  const router = useRouter();

  const [items, setItems] = useState([]);

  useEffect(() => {
    setItems(itemsList);
  }, [itemsList]);

  const handleButtonCLick = (event, value) => {
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        category_id: 100,
      }),
    }

    fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/product/category/`,
      requestOptions,
    )
      .then(response => response.json())
      .then(json => setItems(json));
  }

  return (
    <GuestLayout>
      <div className="py-12">
        <div>
          {items.map((x, i) => (
            {x.price}€
          ))}
        </div>
      </div>
    </GuestLayout>
  );
}


Name.getInitialProps = async context => {
  let valor = 1;

  const { data } = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/product/category/${valor}/`);

  return { itemsList: data };
}

export default Name;
  • Related