React URL param redirect

I am currently working with react and react-router and I'm building a page that shows details of a certain item that gets its data from an API when the page mounts. The fetch method requires the item's id so I'm using match.params.id to get the value for the fetch method. I also am using the slug package in the backend to show the title for that item in URL format alongside the id. I want users to be able to type in the URL with the slug title and not have to worry about typing the id in order to be directed to the page with the correct data.

For example, clicking on the item on the UI will make the URL look like this: localhost:3000/the-title-slug/123456. You have to actually click on the item on the UI to get the URL to have the id but I want to make things simpler for the user and make it so that if they only type the slug title: localhost:3000/the-slug-title, it will redirect to the correct URL with that slug and id.

Any ideas on how this could be done? Kind of like if you type googel.com it corrects the typo and directs you to google.com. Any help figuring this out would be very appreciated, thank you.

1 answer

  • answered 2020-05-22 23:34 IT's Bruise

    Your backend must to have the API method to get correct item by misspelled slug. like:

    requestData: the-slug-title
    responseData: the-title-slug, 123456
    

    and then your component have to handle wrong url

    componentDidMount() {
      const { params } = this.props.match;
    
      const respose = await fetch({ ... })
    
      this.setState({ id: response.id, slug: response.slug });
    }
    
    render() {
      const { params } = this.props.match;
    
      return this.state.id && this.state.slug && (this.state.id !== params.id || this.state.slug !== params.slug) && <Redirect to={`/${this.state.slug}/${this.state.id}`} />
    }