0

I have a URL which should be changing dynamically. The number 2 is dynamic.

const API_Albums = `https://jsonplaceholder.typicode.com/users/2/albums`


class Main extends Component { 
...

  fetchAlbums(id) {
        axios.get(API_Albums+id/albums)
            .then(result => {
               .....
            })
            .catch(error => console.log(error)
            )
    }
}

How can I change only the id's part of URL?

1

1 Answer 1

0

You are looking for a template literal

class Main extends Component { 
...

  fetchAlbums(id) {
        axios.get(`https://jsonplaceholder.typicode.com/users/${id}/albums`)
            .then(result => {
               .....
            })
            .catch(error => console.log(error)
            )
    }
}

Edit

Example using a function outside of the get to make the dynamic url

const buildUrl = id => `https://jsonplaceholder.typicode.com/users/${id}/albums`
class Main extends Component { 
...

  fetchAlbums(id) {
        axios.get(buildUrl(id))
            .then(result => {
               .....
            })
            .catch(error => console.log(error)
            )
    }
}

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

2 Comments

Is there any way to do that not inside get function?
you could make a function to do it, i'll add an edit

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.