0

I'm building out a simple quiz app with a rails api rendering the questions in json and react pulling them in. However I'm not very experienced with react and I'm having trouble working out how to go about getting one question at a time displayed on the screen as the display is the same going to localhost:3000 or localhost:3000/questions/1. Any advice on how to get it using the show method when appropriate instead of index for everything would be really appreciated.

  componentDidMount() {
    axios.get('http://localhost:3001/api/v1/questions.json')
    .then(response => {
      console.log(response)
      this.setState({questions: response.data})
    })
    .catch(error => console.log(error))
  }

1 Answer 1

1

your index route should show all the questions

So:

def index
    questions = Question.all
    however_you_render_json(questions)
end

And your show route should take the id from the URL and show one questions from that

def show
    question = Question.find(params[:id])
    however_you_render_json(question)
end

in your routes.rb file you should have

resources :users

which which automatically create the required routes, you can run bundle exec rake routes in rails console to verify the URI patterns

On the React end, the requests should be: axios.get('http://localhost:3001/api/v1/questions/) for index or axios.get('http://localhost:3001/api/v1/questions/1) for show.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for you response, I have those parts of it in exactly as you've described and the routes are showing in rake routes as they should. For some reason it just won't transfer over into the react to use the show route, it seems to take the index for every address
Can you edit your question to include the calls to your Rails API?
I've added the request in and I see what you mean now, sorry. My request is always grabbing all questions, do I need a separate request to get the question by id?
Your get method seems to be grabbing a static json file from the server. it should be axios.get('http://localhost:3001/api/v1/questions/) for index or axios.get('http://localhost:3001/api/v1/questions/1) for show. Again, check the output of rake routes to determine the proper url
Right, ok, this is making a lot more sense :) Ok, so now I just need to work out how to do multiple views in react, not covered that at all, and use the request for the specific question I need. Awesome, thank you
|

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.