0

I want to get the params value to use it in the frontside, just because in the backside, for each instrument that I search it will return the data of all the instruments that match with the URL

BACKEND:

categorys: async (req, res) => {
        try{
            let categoriaTitulo = await db.Category.findOne({where:{nombre: req.params.category}})
            let instrumentos = await db.Instruments.findAll({where:{categoria_id: categoriaTitulo.id}, include:{association: "imagenes"}},)
            return res.status(200).json({
                titulo: categoriaTitulo,
                instrumentos: instrumentos
            })
        }catch(error){
            console.log(error)
            res.send(error)
        }
    }

// http://localhost:5000/guitarra

{
  "titulo": {
    "id": 1,
    "nombre": "Guitarra"
  },
  "instrumentos": [
    {
      "id": 19,
      "nombre": "SG Special",
      "fabricante": "Epiphone",
      "precio": 104999,
      "descuento": 0,
      "precioDescuento": 0,
      "texto": "SG Special regresa al diseño clásico que lo hizo relevante, tocado y amado, dando forma al sonido a través de generaciones y géneros musicales. Este SG Special de principios de los 60 tiene la vibración y el sonido que se escuchan en innumerables grabaciones de rock clásico.",
      "fecha": "2015-06-15",
      "categoria_id": 1,
      "imagenes": [
        {
          "id": 4,
          "url_imagen": "/SG-Special/images-1643573154488.webp",
          "instrumento_id": 19
        },
        {
          "id": 5,
          "url_imagen": "/SG-Special/images-1643573154489.webp",
          "instrumento_id": 19
        },
        {
          "id": 6,
          "url_imagen": "/SG-Special/images-1643573154490.webp",
          "instrumento_id": 19
        }
      ]
    }

I saw that I can use useSearchParams in a function but not in a class, and in react-router-dom v4 you should use this.props.match.params to bring the value, but I don't know how can I use it in v6, I need this parameter to complete the ComponentDidMount, so for each instrument it will bring all the data.

REACT

<Routes>
            <Route path="/" element={<Home />} />
            <Route path="/crear-instrumento" element={<FormObject />} />
            <Route path="/:category" element={<Categorias />} />
        </Routes>


class Categorias extends Component {
    constructor(props){
        super(props);
        this.state = {
            instrumentos: [],
        }
    };

    
    async componentDidMount(){
        try{
            
            let category = this.props.match.params.category

            let instrumentos = await fetch(`http://localhost:5000/${category}` ).then(response => response.json())

            console.log("llegue", this.props.match);
            
            this.setState({
                titulo: instrumentos.instrumentos,
                instrumentos: instrumentos.instrumentos
            });

        }
        catch(error){
            console.log(error);
        }
    }

Any idea?

Osanda Gamage
  • 446
  • 2
  • 6
  • 16
  • I tried but i had this error ERROR in ./src/components/Instrumentos/categorias.js 61:20-30 export 'withRouter' (imported as 'withRouter') was not found in 'react-router' (possible exports: MemoryRouter, Navigate, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createRoutesFromChildren, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, useHref, useInRouterContext, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes) – Juan Segundo Martínez Feb 06 '22 at 03:41
  • I think your best bet is probably to switch to functional component instead of class based if possible. You can use the `useEffect` hook instead of `componentDidMount`. However, you can see this answer if you really need a workaround https://stackoverflow.com/a/60658888/15038439 – Willow Feb 06 '22 at 04:22
  • At the end, what i did was use an older version of react-router & reac-router-dom as the v6 dosent get the info correctly – Juan Segundo Martínez Feb 07 '22 at 19:12

0 Answers0