简体   繁体   中英

Favorites saving on backend, but against all users not the current user logged in

I am creating an app where one of the functionalities is to make it so that the current user logged in can save a coffee shop to their favorites list. Right now my favorites are currently working, however when it saves on the backend it saves against all users not just the current user logged in. Im using a rails backend with JWT Auth and React frontend. I attempted to correct this by doing something like this in my FavoritesController...

....
 def index
        favorites = Favorite.where(user_id: params[:user_id])
        render json: favorites
    end

and then on the front end trying to grab the user_id in my GET and POST request such as;

Get Request...

...
    componentDidMount() {
      fetch(`http://localhost:3000/favorites?user_id=${user_id}`)
      .then(resp => resp.json())
      .then(favorites => this.setState({ favorites }))
    }

Container...

import React from 'react';
import CoffeeShop from './CoffeeShop'
import NavBar from './NavBar'

class CafesContainer extends React.Component {

  state = {
    cafes: [],
    cafe:{},
    isCafeViewOn: false,
    inputValue: '',
    inputSort: '',
    user: {
      id:0,
      username:'',
      token:'',
    }
}

...

addToFav = (cafe) => {
  console.log(cafe)
  fetch(`http://localhost:3000/favorites?user_id=${user_id}`,{
    method: "POST",
    headers: { 
      "Content-Type" : "application/json",
      Accept: "application/json",
      Authorization: `bearer ${localStorage.token}`
    },
      body: JSON.stringify( cafe )
  })
  .then(res => res.json())
  .then(console.log)
  }

 ...
  
render() {  
  
...

      <input type="text" className="cafe-search-bar" placeholder="Type Cafe Name Here..." value={this.inputValue} onChange={(e) => {this.cafeFilterOnChange(e)}}/>

      <ul>
        {
           filteredCafes.map(cafe => <CoffeeShop cafes={this.filteredCafes} handleCafeView={this.handleCafeView} cafeFilterOnChange={this.cafeFilterOnChange} inputValue={this.inputValue}
           addToFav={this.addToFav} key={cafe.id} cafe={cafe} />)
        }  
      </ul>
     </div>
    )
  }
}
;
  export default CafesContainer;

However when I try to do his way against by fetching the user_id and posting with the user_id I get a error on the frontend stating

'user_id' is not defined  no-undef

from what im gathering its not getting the state of the user even tho im setting at the top in state, im able to get this to work if I do something like this

   componentDidMount() {
      fetch(`http://localhost:3000/favorites`)
      .then(resp => resp.json())
      .then(favorites => this.setState({ favorites }))
    }

...

addToFav = (cafe) => {
  console.log(cafe)
  fetch(`http://localhost:3000/favorites`,{
    method: "POST",
    headers: { 
      "Content-Type" : "application/json",
      Accept: "application/json",
      Authorization: `bearer ${localStorage.token}`
    },
      body: JSON.stringify( cafe )
  })
  .then(res => res.json())
  .then(console.log)
  }

but this is setting it for all users not just the current user logged in..

Any advise would be great!!

Thank you!

I did not find where are you calling the index method to get the list of favorites of a certain user but wherever that is you have to pass the user ID as a param. something like:

http://localhost:3000/favorites?user_id=${user_id}

I would also recommend adding a.sort at the end of the query in the controller so that you can control the logic of how the list of favorites appear (date added to favorites, cafe name, etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM