Issue
I have a component that I want to reuse with different Axios clients.
Example:
var first_instance = axios.create({
baseURL: 'https://bank_one.com/api'
});
var second_instance = axios.create({
baseURL: 'https://bank_two.com/api'
});
const clients = {
first_instance,
second_instance
};
export default clients;
I have a component and I want to be able to pass one of these instances as a prop or object. Something like this:
function BankClient({clients}){
handleSubmit = event => {
event.preventDefault();
const user = {
name: this.state.name
};
clients.first_instance.get(`/accounts`, { user })
.then(res => {
console.log(res);
console.log(res.data);
})
}
return(
//etc etc
)
}
I've tried using this blog to pass objects as props but it doesn't seem to be working
Solution
Pass the Axios instance you want to use in the component as a prop. For example...
import clients from "./path/to/axios-clients";
import BankClient from "./BankClient";
const App = () => (
<BankClient client={client.first_instance} />
);
Within the component, use props.client
to access it
import { useState } from "react";
const BankClient = ({ client }) => { // destructure props.client
const [username, setUsername] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
const { data } = await client.get(
`/accounts/${encodeURIComponent(username)}`
);
console.log(data);
};
return (
{/* ... */}
);
};
export default BankClient;
You appear to want to use function components so be aware that the syntax is a little different to class based components.
The main thing is that you use plain functions and hooks instead of methods and this.state
.
Answered By - Phil Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.