0

I am using React JS to program a search bar, where a user can type in information and it takes them to a search results page. Here is my code:

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Box, Typography } from '@mui/material';
import Item from './Item';

function SearchResults() {
  const { keywords } = useParams();
  const navigate = useNavigate();
  const [searchResults, setSearchResults] = useState([]);

  useEffect(() => {
    fetchSearchResults();
  }, [keywords]);

  const fetchSearchResults = async () => {
    try {
      const response = await fetch(
        `http://localhost:1337/api/items?populate=image&q=${keywords}`
      );
      const data = await response.json();
      console.log('Fetched data:', data);
      setSearchResults(Array.isArray(data.data) ? data.data : []);
    } catch (error) {
      console.error('Error fetching search results:', error);
    }
  };

  const renderRelatedItems = () => {
    const relatedItems = searchResults.slice(0, 4);
    console.log('Related items:', relatedItems);

    return relatedItems.map((result, i) => (
      <Item key={`${result.name}-${i}`} item={result} />
    ));
  };

  return (
    <div>
      <h2 style={{ marginTop: '35px', textAlign: 'center' }}></h2>

      {searchResults.length === 0 ? (
        <p>No results found.</p>
      ) : (
        <div>
          <Box mt="50px" width="100%">
            <Typography variant="h3" fontWeight="bold" textAlign="center">
              Search Results Keywords for: {keywords} 
            </Typography>
            <Box
              mt="20px"
              display="flex"
              flexWrap="wrap"
              columnGap="1.33%"
              justifyContent="space-between"
            >
              {renderRelatedItems()}
            </Box>
          </Box>
          <div className="search-results">
            {searchResults.map((result) => (
              <div key={result.id} className="search-result">
                <h3>{result.name}</h3>
                <p>{result.description}</p>
                {/* Render any other information you want to display */}
              </div>
            ))}
          </div>
        </div>
      )}

      <button onClick={() => navigate(-1)}>Go Back</button>
    </div>
  );
}

export default SearchResults;`


The page looks like this:

Website

My problem is that I want the information displayed to match what the user typed in. However, anytime I type in a keyword, it will continue to display the same 4/9 images, that are found in the API: http://localhost:1337/api/items?populate=image connected to Strapi backend. It has this information within it:

{"data":[{"id":1,"attributes":{"name":"Black & Gold Bracelet","shortDescription":"This black and gold ring is a bold and elegant piece of jewelry that is sure to turn heads","longDescription":"This black and gold ring is a stunning piece of jewelry that will add a touch of elegance to any outfit. The combination of black and gold creates a bold contrast that is both modern and timeless. The ring is made from high-quality materials that are designed to last for years to come","price":15,"category":"bestSellers","createdAt":"2023-06-07T01:45:30.465Z","updatedAt":"2023-06-07T12:23:30.175Z","publishedAt":"2023-06-07T01:45:41.305Z","image":{"data":{"id":10,"attributes":{"name":"bracelet1.jpg","alternativeText":null,"caption":null,"width":8481,"height":6336,"formats":{"thumbnail":{"name":"thumbnail_bracelet1.jpg","hash":"thumbnail_bracelet1_c5dbe6918d","ext":".jpg","mime":"image/jpeg","path":null,"width":209,"height":156,"size":2.8,"url":"/uploads/thumbnail_bracelet1_c5dbe6918d.jpg"},"large":{"name":"large_bracelet1.jpg","hash":"large_bracelet1_c5dbe6918d","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":747,"size":28.32,"url":"/uploads/large_bracelet1_c5dbe6918d.jpg"},"medium":{"name":"medium_bracelet1.jpg","hash":"medium_bracelet1_c5dbe6918d","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":560,"size":17.79,"url":"/uploads/medium_bracelet1_c5dbe6918d.jpg"},"small":{"name":"small_bracelet1.jpg","hash":"small_bracelet1_c5dbe6918d","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":374,"size":9.75,"url":"/uploads/small_bracelet1_c5dbe6918d.jpg"}},"hash":"bracelet1_c5dbe6918d","ext":".jpg","mime":"image/jpeg","size":1585.46,"url":"/uploads/bracelet1_c5dbe6918d.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:13.700Z","updatedAt":"2023-06-07T01:45:13.746Z"}}}}},{"id":2,"attributes":{"name":"Heart Necklace","shortDescription":"This heart necklace is a beautiful piece of jewelry that is perfect for any occasion. ","longDescription":"This heart necklace is a beautiful piece of jewelry that is perfect for any occasion. The necklace features a stunning heart-shaped pendant that is sure to catch the eye. It is made from high-quality materials that are designed to last for years to come.","price":15,"category":"newArrivals","createdAt":"2023-06-07T01:48:17.707Z","updatedAt":"2023-06-07T12:24:57.602Z","publishedAt":"2023-06-07T01:48:19.168Z","image":{"data":{"id":2,"attributes":{"name":"necklace2.jpg","alternativeText":null,"caption":null,"width":4969,"height":3313,"formats":{"thumbnail":{"name":"thumbnail_necklace2.jpg","hash":"thumbnail_necklace2_6a47bc5957","ext":".jpg","mime":"image/jpeg","path":null,"width":234,"height":156,"size":2.06,"url":"/uploads/thumbnail_necklace2_6a47bc5957.jpg"},"large":{"name":"large_necklace2.jpg","hash":"large_necklace2_6a47bc5957","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":667,"size":18.98,"url":"/uploads/large_necklace2_6a47bc5957.jpg"},"small":{"name":"small_necklace2.jpg","hash":"small_necklace2_6a47bc5957","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":333,"size":6.02,"url":"/uploads/small_necklace2_6a47bc5957.jpg"},"medium":{"name":"medium_necklace2.jpg","hash":"medium_necklace2_6a47bc5957","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":500,"size":11.71,"url":"/uploads/medium_necklace2_6a47bc5957.jpg"}},"hash":"necklace2_6a47bc5957","ext":".jpg","mime":"image/jpeg","size":517.77,"url":"/uploads/necklace2_6a47bc5957.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:07.152Z","updatedAt":"2023-06-07T00:01:07.152Z"}}}}},{"id":3,"attributes":{"name":"Blue & Silver Ring","shortDescription":"This stunning ring features a beautiful emerald stone set in a silver band. ","longDescription":"This stunning ring features a beautiful emerald stone set in a silver band. The blue-silver color combination is unique and eye-catching, making it the perfect accessory for any outfit. The emerald stone is known to symbolize mercy, compassion, and universal love, promoting physical, emotional, mental, and spiritual balance. ","price":25,"category":"bestSellers","createdAt":"2023-06-07T01:50:35.718Z","updatedAt":"2023-06-07T12:23:41.446Z","publishedAt":"2023-06-07T01:50:36.471Z","image":{"data":{"id":6,"attributes":{"name":"ring3.jpg","alternativeText":null,"caption":null,"width":2868,"height":1912,"formats":{"thumbnail":{"name":"thumbnail_ring3.jpg","hash":"thumbnail_ring3_3815864db0","ext":".jpg","mime":"image/jpeg","path":null,"width":234,"height":156,"size":3.07,"url":"/uploads/thumbnail_ring3_3815864db0.jpg"},"large":{"name":"large_ring3.jpg","hash":"large_ring3_3815864db0","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":667,"size":34.96,"url":"/uploads/large_ring3_3815864db0.jpg"},"medium":{"name":"medium_ring3.jpg","hash":"medium_ring3_3815864db0","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":500,"size":21.31,"url":"/uploads/medium_ring3_3815864db0.jpg"},"small":{"name":"small_ring3.jpg","hash":"small_ring3_3815864db0","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":333,"size":10.58,"url":"/uploads/small_ring3_3815864db0.jpg"}},"hash":"ring3_3815864db0","ext":".jpg","mime":"image/jpeg","size":259.85,"url":"/uploads/ring3_3815864db0.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:10.615Z","updatedAt":"2023-06-07T01:50:26.872Z"}}}}},{"id":4,"attributes":{"name":"Reddish Gold Ring","shortDescription":"This gorgeous ring features a stunning red stone set in a luxurious gold band. ","longDescription":"This gorgeous ring features a stunning red stone set in a luxurious gold band. The red-gold color combination is unique and eye-catching, making it the perfect accessory for any outfit. The red stone is known to symbolize passion, love, and energy, making it the perfect gift for someone special. The gold band adds a touch of elegance and sophistication to the ring, making it perfect for formal occasions or everyday wear.","price":120,"category":"topRated","createdAt":"2023-06-07T01:52:45.972Z","updatedAt":"2023-06-07T12:25:19.915Z","publishedAt":"2023-06-07T01:52:46.688Z","image":{"data":{"id":8,"attributes":{"name":"ring2.jpg","alternativeText":null,"caption":null,"width":3243,"height":3243,"formats":{"thumbnail":{"name":"thumbnail_ring2.jpg","hash":"thumbnail_ring2_12b7d06f1e","ext":".jpg","mime":"image/jpeg","path":null,"width":156,"height":156,"size":3.35,"url":"/uploads/thumbnail_ring2_12b7d06f1e.jpg"},"medium":{"name":"medium_ring2.jpg","hash":"medium_ring2_12b7d06f1e","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":750,"size":46.07,"url":"/uploads/medium_ring2_12b7d06f1e.jpg"},"large":{"name":"large_ring2.jpg","hash":"large_ring2_12b7d06f1e","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":1000,"size":83.01,"url":"/uploads/large_ring2_12b7d06f1e.jpg"},"small":{"name":"small_ring2.jpg","hash":"small_ring2_12b7d06f1e","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":500,"size":22.34,"url":"/uploads/small_ring2_12b7d06f1e.jpg"}},"hash":"ring2_12b7d06f1e","ext":".jpg","mime":"image/jpeg","size":1400.7,"url":"/uploads/ring2_12b7d06f1e.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:12.990Z","updatedAt":"2023-06-07T00:01:12.990Z"}}}}},{"id":5,"attributes":{"name":"Platinum Ring","shortDescription":"This stunning platinum ring is the perfect accessory for any occasion. ","longDescription":"This stunning platinum ring is the perfect accessory for any occasion. The platinum band is known for its durability and strength, making it perfect for everyday wear. The ring is also set with a beautiful stone that adds a touch of elegance and sophistication to the piece. Platinum is a rare and valuable metal, making this ring a great investment that will last a lifetime.","price":150,"category":"topRated","createdAt":"2023-06-07T01:54:16.577Z","updatedAt":"2023-06-07T12:25:34.371Z","publishedAt":"2023-06-07T01:54:17.384Z","image":{"data":{"id":5,"attributes":{"name":"ring1.jpg","alternativeText":null,"caption":null,"width":3505,"height":2337,"formats":{"thumbnail":{"name":"thumbnail_ring1.jpg","hash":"thumbnail_ring1_08ea8fdcf0","ext":".jpg","mime":"image/jpeg","path":null,"width":234,"height":156,"size":3.4,"url":"/uploads/thumbnail_ring1_08ea8fdcf0.jpg"},"large":{"name":"large_ring1.jpg","hash":"large_ring1_08ea8fdcf0","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":667,"size":40.18,"url":"/uploads/large_ring1_08ea8fdcf0.jpg"},"medium":{"name":"medium_ring1.jpg","hash":"medium_ring1_08ea8fdcf0","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":500,"size":24.55,"url":"/uploads/medium_ring1_08ea8fdcf0.jpg"},"small":{"name":"small_ring1.jpg","hash":"small_ring1_08ea8fdcf0","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":333,"size":12.04,"url":"/uploads/small_ring1_08ea8fdcf0.jpg"}},"hash":"ring1_08ea8fdcf0","ext":".jpg","mime":"image/jpeg","size":376.26,"url":"/uploads/ring1_08ea8fdcf0.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:10.109Z","updatedAt":"2023-06-07T00:01:10.109Z"}}}}},{"id":6,"attributes":{"name":"Diamond Bracelet","shortDescription":"This stunning diamond bracelet is the perfect accessory for any occasion","longDescription":"This stunning diamond bracelet is the perfect accessory for any occasion. The bracelet is set with 38 full cut diamonds that are prong-set and have a total weight of 2.00 carats 1. The diamonds have a wonderful clarity of SI2-I1 and a near colorless H-I color 1. The bracelet is made of solid 14kt white gold and has interlocking links that add to its beauty and elegance ","price":35,"category":"bestSellers","createdAt":"2023-06-07T01:55:44.284Z","updatedAt":"2023-06-07T12:24:01.526Z","publishedAt":"2023-06-07T01:55:45.178Z","image":{"data":{"id":3,"attributes":{"name":"bracelet3.jpg","alternativeText":null,"caption":null,"width":4724,"height":3149,"formats":{"thumbnail":{"name":"thumbnail_bracelet3.jpg","hash":"thumbnail_bracelet3_9f3346b903","ext":".jpg","mime":"image/jpeg","path":null,"width":234,"height":156,"size":3.86,"url":"/uploads/thumbnail_bracelet3_9f3346b903.jpg"},"large":{"name":"large_bracelet3.jpg","hash":"large_bracelet3_9f3346b903","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":666,"size":38.07,"url":"/uploads/large_bracelet3_9f3346b903.jpg"},"medium":{"name":"medium_bracelet3.jpg","hash":"medium_bracelet3_9f3346b903","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":500,"size":23.54,"url":"/uploads/medium_bracelet3_9f3346b903.jpg"},"small":{"name":"small_bracelet3.jpg","hash":"small_bracelet3_9f3346b903","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":333,"size":12.14,"url":"/uploads/small_bracelet3_9f3346b903.jpg"}},"hash":"bracelet3_9f3346b903","ext":".jpg","mime":"image/jpeg","size":614.3,"url":"/uploads/bracelet3_9f3346b903.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:07.919Z","updatedAt":"2023-06-07T00:01:07.919Z"}}}}},{"id":7,"attributes":{"name":"Gold Bracelet","shortDescription":"This bracelet is made of high-quality gold that has been crafted to perfection","longDescription":"This ultra fine gold bracelet is a beautiful and elegant piece of jewelry that is perfect for any occasion. The ring is made of high-quality gold that has been crafted to perfection. The ring is designed to be ultra-fine, which makes it comfortable to wear and easy to pair with other jewelry pieces","price":60,"category":"newArrivals","createdAt":"2023-06-07T02:01:41.200Z","updatedAt":"2023-06-07T12:24:18.015Z","publishedAt":"2023-06-07T02:05:18.420Z","image":{"data":{"id":7,"attributes":{"name":"bracelet2.jpg","alternativeText":null,"caption":null,"width":5184,"height":3456,"formats":{"thumbnail":{"name":"thumbnail_bracelet2.jpg","hash":"thumbnail_bracelet2_6626780d5e","ext":".jpg","mime":"image/jpeg","path":null,"width":234,"height":156,"size":4,"url":"/uploads/thumbnail_bracelet2_6626780d5e.jpg"},"large":{"name":"large_bracelet2.jpg","hash":"large_bracelet2_6626780d5e","ext":".jpg","mime":"image/jpeg","path":null,"width":1000,"height":667,"size":46.01,"url":"/uploads/large_bracelet2_6626780d5e.jpg"},"small":{"name":"small_bracelet2.jpg","hash":"small_bracelet2_6626780d5e","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":333,"size":13.35,"url":"/uploads/small_bracelet2_6626780d5e.jpg"},"medium":{"name":"medium_bracelet2.jpg","hash":"medium_bracelet2_6626780d5e","ext":".jpg","mime":"image/jpeg","path":null,"width":750,"height":500,"size":27.08,"url":"/uploads/medium_bracelet2_6626780d5e.jpg"}},"hash":"bracelet2_6626780d5e","ext":".jpg","mime":"image/jpeg","size":1502.73,"url":"/uploads/bracelet2_6626780d5e.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:11.841Z","updatedAt":"2023-06-07T00:01:11.841Z"}}}}},{"id":8,"attributes":{"name":"Platinum Necklace","shortDescription":"This necklace is designed to be elegant and timeless. ","longDescription":"This platinum necklace is a stunning piece of jewelry that is perfect for any occasion. The necklace is made of high-quality platinum that has been crafted to perfection. The necklace is designed to be elegant and timeless, which makes it a great addition to any jewelry collection.","price":100,"category":"topRated","createdAt":"2023-06-07T02:03:43.455Z","updatedAt":"2023-06-07T12:25:11.266Z","publishedAt":"2023-06-07T02:03:45.125Z","image":{"data":{"id":4,"attributes":{"name":"necklace1.jpg","alternativeText":null,"caption":null,"width":3208,"height":4812,"formats":{"thumbnail":{"name":"thumbnail_necklace1.jpg","hash":"thumbnail_necklace1_8e9e8ae9e2","ext":".jpg","mime":"image/jpeg","path":null,"width":104,"height":156,"size":1.84,"url":"/uploads/thumbnail_necklace1_8e9e8ae9e2.jpg"},"large":{"name":"large_necklace1.jpg","hash":"large_necklace1_8e9e8ae9e2","ext":".jpg","mime":"image/jpeg","path":null,"width":667,"height":1000,"size":30.89,"url":"/uploads/large_necklace1_8e9e8ae9e2.jpg"},"medium":{"name":"medium_necklace1.jpg","hash":"medium_necklace1_8e9e8ae9e2","ext":".jpg","mime":"image/jpeg","path":null,"width":500,"height":750,"size":18.77,"url":"/uploads/medium_necklace1_8e9e8ae9e2.jpg"},"small":{"name":"small_necklace1.jpg","hash":"small_necklace1_8e9e8ae9e2","ext":".jpg","mime":"image/jpeg","path":null,"width":334,"height":500,"size":9.45,"url":"/uploads/small_necklace1_8e9e8ae9e2.jpg"}},"hash":"necklace1_8e9e8ae9e2","ext":".jpg","mime":"image/jpeg","size":870.24,"url":"/uploads/necklace1_8e9e8ae9e2.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:08.699Z","updatedAt":"2023-06-07T00:01:08.699Z"}}}}},{"id":9,"attributes":{"name":"Gold Necklace","shortDescription":"This gold necklace is a stunning piece of jewelry that is perfect for any occasion. ","longDescription":"This gold necklace is a stunning piece of jewelry that is perfect for any occasion. The necklace is made of high-quality gold that has been crafted to perfection. The necklace is designed to be elegant and timeless, which makes it a great addition to any jewelry collection.","price":80,"category":"newArrivals","createdAt":"2023-06-07T02:04:57.568Z","updatedAt":"2023-06-07T12:24:39.368Z","publishedAt":"2023-06-07T02:05:22.826Z","image":{"data":{"id":1,"attributes":{"name":"necklace3.jpg","alternativeText":null,"caption":null,"width":2658,"height":3323,"formats":{"thumbnail":{"name":"thumbnail_necklace3.jpg","hash":"thumbnail_necklace3_f61b54bcb1","ext":".jpg","mime":"image/jpeg","path":null,"width":125,"height":156,"size":2.55,"url":"/uploads/thumbnail_necklace3_f61b54bcb1.jpg"},"medium":{"name":"medium_necklace3.jpg","hash":"medium_necklace3_f61b54bcb1","ext":".jpg","mime":"image/jpeg","path":null,"width":600,"height":750,"size":31.4,"url":"/uploads/medium_necklace3_f61b54bcb1.jpg"},"large":{"name":"large_necklace3.jpg","hash":"large_necklace3_f61b54bcb1","ext":".jpg","mime":"image/jpeg","path":null,"width":800,"height":1000,"size":50.78,"url":"/uploads/large_necklace3_f61b54bcb1.jpg"},"small":{"name":"small_necklace3.jpg","hash":"small_necklace3_f61b54bcb1","ext":".jpg","mime":"image/jpeg","path":null,"width":400,"height":500,"size":16.04,"url":"/uploads/small_necklace3_f61b54bcb1.jpg"}},"hash":"necklace3_f61b54bcb1","ext":".jpg","mime":"image/jpeg","size":682.18,"url":"/uploads/necklace3_f61b54bcb1.jpg","previewUrl":null,"provider":"local","provider_metadata":null,"createdAt":"2023-06-07T00:01:07.068Z","updatedAt":"2023-06-07T00:01:07.068Z"}}}}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":9}}}

I used the following youtube video to create my project, but he does not create a relevant search bar:

https://www.youtube.com/watch?v=EBCdyQ_HFMo&t=14010s

Thank you for your assistance!

Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
  • 1
    In what specific way is the code not working as expected? Does the AJAX request to the API not include the expected "keyword" value? Do the results received from the API not match what you expect? I don't see any logic shown which otherwise filters results. Which specific operation in the code shown isn't doing what you expect? – David Jun 08 '23 at 18:31
  • I want it so that when a user types in e.g., "Bracelet", the api pulls the relevant data and then displays the information on the page. Thus to answer your question, the results received from the API do not match what I expect. I'm not sure where I would start in accomplishing this. The results from the API will display the same 4/9 of the images in the array. – Chris Keightley Jun 08 '23 at 18:35
  • If your goal is for the API (the server-side code) to filter results based on that keyword then you'd start there. In which case the code shown sounds like it's working as designed. – David Jun 08 '23 at 18:38
  • OK, so it sounds like the front-end code is fine but the back-end isn't returning data based on the keyword you're sending in the request. I don't know how Strapi works but that's where my initial checks would start. – Andy Jun 08 '23 at 18:40
  • Thank you for the assistance. Note that I did not design the code myself, I am a complete beginner. The code displays 4/9 objects in the array. However, what is being displayed is not relevant to the search word. For example, black and gold bracelet, heart necklace, and blue silver ring continue to be fetched, regardless of what keyword I type into the search bar. – Chris Keightley Jun 08 '23 at 18:42
  • Thank you Andy. – Chris Keightley Jun 08 '23 at 18:43
  • Strapi creates an API that stores all of the relevant data. You can see in the file I posted that it stores the object "name: Black & Gold Bracelet", I want my search to be based on the name, and for the API to pull all of the relevant info. – Chris Keightley Jun 08 '23 at 18:45
  • @ChrisKeightley: Please see [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/q/284236/328193) You are encouraged to make an attempt. If during your attempt you encounter a specific problem, such as a specific operation producing an error or an unexpected result, we can help with that. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Jun 08 '23 at 18:48

0 Answers0