PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How can I pass an Axios instance as an object or prop into a React component?

 October 13, 2022     axios, reactjs     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing