Consuming rest api with axios

Viewed 113

I'll like to consume a rest api with axios in react native. I'll like to get an specific item so the URL is as follows /book/637777378 how do I pass that number id with axios.

What I have done till now:

import axios from 'axios';
import config from '../Config'

const requestHelper = axios.create({
    baseURL: config.prodBaseUrl,
});

export default {
    books: {
        getAll: () => requestHelper({
            url: 'books',
            method: 'get',
        }),
        getOne: bookId => requestHelper({
            url: 'books/' + bookId, // '5f914f39342ba5b506cb386f',
            method: 'get',
        }),
        create: data => requestHelper({
            url: 'books',
            method: 'post',
            data,
        }),
    },
};

the code as is DO NOT work. But DO works if I hardcode the book id as :

url: 'books/' + '5f914f39342ba5b506cb386f',

to call the action I do:

const bookId = this.props.navigation.getParam('bookId')

console.log(bookId);   // The bookId is NOT NULL. Is CORRECT!

getChatRoom(bookId);

Where is my mistake?

Thanks

1 Answers

Change the URL as follows using backticks instead of single quotes

url: `books/${bookId}`

bookId is the variable. To add a variable inside a string, you have to use backticks and place the variable inside ${variable_name}

Related