1

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([])

1 Answer 1

4

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

4 Comments

I have tried that and it does not give an error, but it does not send the JSON with the items to the component since the component receives {itemsList} as props, so if I make a set of items with setItems it does not refresh the data on the screen.
@ilernet2 Can you clarify what isn't refreshing on screen? As far as I can see, neither the itemsList nor any local state is used in the component. You are using two different endpoints. What are you trying to pass, fetch, and render?
I load the endpoint data into the props itemsList , the first time I load the component (this works fine). I also have a search button with the "handleButtonCLick" event that makes an API call with parameters and returns a JSON. This json that it returns is the one that I try to put in itemsList to refresh the data on the screen.
@ilernet2 Ok, I think I understand. Please see my updated answer.

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.