useStripe does not return all API methods - reactjs

I'm currently working on refactoring old code that uses the Stripe API.
I'm working with nextjs and the useStripe hook, however in the old code (in the backend), the:
const stripeApi = new Stripe(config);
instance was able to access methods such as:
stripeApi.customers.list(options)
Right now I am successfully calling the hook:
const stripe = useStripe();
It returns many usable methods but it does not allow me to access customers for example, am I initiating the instance in the wrong way, are they different instances?

useStripe is something from the client-side Stripe.js library, but things related to customers require the server-side stripe-node library.

Related

How to connect React native with django rest api

I build a simple django rest api now i need to fetch data from it in frontend using React Native.
I can make a request to the api but the data is not coming from there.
I search about it a lot but didn't find any help
Thanks in advance...
npm install axios
const axios = require('axios')
export const App = () =>{
const Your_Request = () =>{
const config= {
method:'get',
url:'YOUR URL',
}
axios(config).then((response)=>{
console.log('response',response)
}).catch((error)=>{
console.log('error',error)})
}
return (<View></View>)
}
You should first try to see whether your API works correctly.
I can recommend you Postman (https://www.postman.com/) for that.
It's free, comes with an intuitive GUI, and allows you to make requests to your API, see the returned data, status codes, headers, and so on.
Once the API returns the data correctly, you'll need to fetch the data in the React application. For that you can either place fetch() requests in the respective lifecycle methods, although this will get burdensome quite quickly if you need authentication, etc..
Another option would be to build service infrastructure using React hooks to share state (such as API tokens) across the component tree.
Here's a post I wrote on how to do that: https://schneider-lukas.com/blog/react-connect-rest-api.

ReactFire / Firebase Hook Placement

I would like to know of a good way to organize reactfire hooks (such as useUser or useFirestoreCollectionData) in a medium-sized application:
I could put hooks in a top-level component, and pass this information as props down to subcomponents (or use a Context to store state).
I could put hooks within each component when needed, so I would end up with multiple useUser or useFirestoreCollectionData hooks.
The second approach decouples some of the components, which is nice since our project is under active development.
However, I am not sure if reactfire or firebase client library has built-in deduplication, compared to libraries such as SWR or react-query. I would prefer to minimize unnecessary reads.
I like to use a offline first approach when using the Firebase databases. None of the awailable libraries could fit our needs so I made my own list of providers where all of them are decoupled. The main goal was:
to have all data awailable offline no matter if the app is online or not (this also increases response time for users)
to persist realtime listeners for RTDB and Firestore
when you have for example a list and go to a single item and back you probably don't want to stop the listener when leaving that list component and start it again when comming back. If you stop and start it the firebase SKD will load all data from the database.
You can find the providers and an example app here.

When your API is not ready - React + Redux + Axios

This question may be vague, but I thought would help organize my thoughts:
I am setting up the Redux store for a project. Along with the store setup I am setting up an endpoint I have the swagger file for. However, the API is not live just yet. I was wondering how do I set this up with test data in the meantime so when the API is ready, I am able to quickly update.
I would define a Client class or object that interacts with your API. Maybe it has specific functions like .getUser(id) or maybe they are move vague like .getEntity('user', id). This provides a layer of abstraction so that instead of calling axios.get('my-api/users/${id}') in your thunk actions you can call client.getUser(id).
You will have two separate versions of a Client that fit the same interface (this is a lot easier to enforce if using typescript). One will query your actual API while the other just returns mock data. Since they both act the same, it should be easy to switch from one to the other when you are ready. You will have some file where you create and export a client variable.
export const client = new APIClient();
or
export const client = new MockClient();
When you import this client to use in other files, it shouldn't matter which one it is because they both share the same Client interface.

How to share redux store in micro frontend architecture?

I am trying to create a small project to implement micro-frontend architecture following Micro Frontends article. I am creating multiple repositories for each MFE(Micro frontend) and also using Redux for the application. I have the following architecture:
Frame - A centralised(main) repo that is responsible for rendering the main application part and MFEs based on routing(I am using connected-react-router). It initialises the Redux store and also adds an injectReducer function to dynamically add reducers as explained in code splitting in redux docs. The frame fetches the manifest for particular MFE and renders it. The frame also has some redux data for authentication purpose.
MFEs - These are the individual feature-wise application and are rendered by frame.
Now I have a problem that I want to use injectReducer function into my MFEs to dynamically add reducers to store. For this, I need access to the same store instance that is created by frame.
As mentioned in this answer, the ideal way is to export the created store instance and use it but how we can share the same instance of the store across multiple repos?
There is a comment in the article addressing this directly:
If you are using redux, the usual approach is to have a single, global, shared store for the entire application. However, if each micro frontend is supposed to be its own self-contained application, then it makes sense for each one to have its own redux store. The redux docs even mention "isolating a Redux app as a component in a bigger application" as a valid reason to have multiple stores.
Long story short: Don't share your redux store
Sharing anything between your micro frontends no longer makes them separate entities and defeats the entire purpose of it. Now it's just an overengineered monolith. Just turn those respective repos into well-defined modules inside a monolith repo. It is still possible to split responsibilities into their own silos in a unified repo. It just takes more discipline.
Use synthetic events for cross micro frontends communication using eventListeners and CustomEvent like below:
MF-1:
function Cart() {
const [cartItems, addCartItems] = useState([]);
const handleAddToCart = (event) => {
addCartItems((currentItems) => [...currentItems,
event.detail.item]);
};
useEffect(() => {
window.addEventListener('addToCart', handleAddToCart);
return () => {
window.removeEventListener('addToCart', handleAddToCart)
}
}, [handleAddToCart]);
...
}
MF-2:
function itemLookUp() {
const handleSubmit = (item) => {
const customEvent = new CustomEvent('message', { detail: item });
window.dispatchEvent(customEvent)
}
...
}
You can take a look at this NPM package. This package would allow each Micro Frontend to have its own redux store but allow other Micro Frontends to see and subscribe to state changes of other Micro Frontends.
Github
https://github.com/microsoft/redux-micro-frontend
NPM
https://www.npmjs.com/package/redux-micro-frontend
Article
https://www.codezap.dev/post/state-management-ii-world-of-micro-frontends
Might solve your problem.

Storing "global" object outside of Redux store in React/Redux app

I am building a React/Redux app that needs a globally available object (a websocket lib instance). I originally tried to store this in the Redux state tree, however, the instance is not immutable and it caused lots of problems with hot reloading during development (tons of circular reference errors that don't exist when running from compiled code).
My question is how to store/create this instance so that it is available to my Redux code and React components? I could create it at the very top of the component tree and pass it down the tree as a prop, but that feels very "dirty" after doing everything with react-redux connect.
Is there a better way to do this?
#sheeldotme's answer will work well if you're using thunks.
Also keep in mind that, depending on the websocket lib you're using, you may not need the instance as a global variable. For example, with socket.io-client, after your initial io(url) call that makes the websocket connection, any subsequent calls to io(url) (with the same url argument) will return that same connection (i.e. socket object) from memory, without having to reconnect. It makes it easy to have an API that you can simply import/require, rather than having to pass the instance around or make it global. See the socket.io docs for more info.
For example:
socket.js
import io from 'socket.io-client'
const socket = io(`${protocol}//${hostname}:${port}`)
export default socket
Now you can simply import/require your socket.js file to have easy access to the same socket object from anywhere.
Redux Thunk, authored by gaeron, he who authored redux, since 2.1.0 allows you to do:
const store = createStore(
reducer,
applyMiddleware(thunk.withExtraArgument(api))
)
// later
function fetchUser(id) {
return (dispatch, getState, api) => {
// you can use api here
}
}
This is straight from the docs, see the link below for more information:
https://github.com/gaearon/redux-thunk

Resources