This question already has answers here:
Where can I make API call with hooks in react?
(5 answers)
Closed 3 years ago.
I am using the following component:
export const Home =() =>
<div className="cardBox" style={styleBox}>
<CardTrail></CardTrail>
<CardTrail></CardTrail>
<CardTrail></CardTrail>
<Footer></Footer>
</div>
and I am was trying to make a get API request using AJAX. Cant find a suitable way to do it with functional components. I achieved it with class components via the help of componentDidMount() lifecycle method.
The equivalent in a functional component if using React 16.8 or higher is to use an effect with an empty dependency list:
React.useEffect(() => {
// ajax call here
}, [])
Related
I have mixed application that uses Apollo for both React and non-react code.
However, I can’t find documentation or code examples around testing non-react code with the apollo client,not using MockedProvider. I did, however, notice that apollo exports a mock client from the testing directory.
import { createMockClient } from '#apollo/client/testing';
I haven’t found any documentation about this API and am wondering if it’s intended to be used publicly and, if not, what the supported approach is for this.
The reason I need this is simple: When using Next.js’ SSR and/or SSG features data fetching and actual data rendering are split into separate functions.
So the fetching code is not using React, but Node.js to fetch data.
Therefore I use apolloClient.query to fetch the data I need.
When trying to wrap a react component around that fetching code in a test an wrap MockedProvider around that the apolloClient’s query method always returns undefined for mocked queries - so it seems this only works for the useQuery hook?
Do you have any idea how to mock the client in non-react code?
Thank you for your support in advance. If you need any further information from me feel free to ask.
Regards,
Horstcredible
I was in a similar position where I wanted to use a MockedProvider and mock the client class, rather than use useQuery as documented here: https://www.apollographql.com/docs/react/development-testing/testing/
Though it doesn't seem to be documented, createMockClient from '#apollo/client/testing' can be passed the same mocks as MockedProvider to mock without useQuery. These examples assume you have a MockedProvider:
export const mockGetAssetById = async (id: Number): Promise<any> => {
const client = createMockClient(mocks, GetAsset)
const data = await client.query({
query: GetAsset,
variables: id,
})
return data
}
Accomplishes the same as:
const { data } = useQuery(
GetAsset,
{ variables: { id } }
)
This question already has an answer here:
Assert exists().exists returns assert evaluated to false even locator is available in DOM
(1 answer)
Closed 1 year ago.
Im confused about which method to use that gives result about if there is button present or not using karate ui automation. Im confused between using exists() and optional(). Can anyone help!!
This is explained in the documentation: https://github.com/intuit/karate/tree/master/karate-core#optional
If all you need to do is check if a button exists, use exists() like this:
* def flag = exists('#myButton')
# now you can use the value of flag to perform logic
Ask a new question with specifics if needed.
Im using Create React App and have set up my test files like this:
import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Then I set up wrapper using shallow() like this:
let wrapper;
beforeEach(() => {
const defaultProps = {
color: 'orange',
value: 17,
title: 'live services',
link: 'htttp://google.com'
};
wrapper = shallow(<Callout {...defaultProps} />);
});
Im using assertions that I have been using for a while such as
expect(wrapper.find('h5').html()).toContain('some title');
expect(wrapper.containsMatchingElement(<Foo />)).toBe(true);
These assertions work but i want to find more.
I have no idea where to find the docs for the assertions that are available to me.
The assertions I have working so far look a bit like Jasmine assertions in that they are using camel case but the methods are still named differently.
https://jasmine.github.io/
I thought I was using jest and enzyme but the assertions are completely different to those in the Enzyme docs
https://airbnb.io/enzyme/
For example
expect(wrapper.find(Foo)).to.have.lengthOf(3);
Does not work. These methods of find() are not available to my current set up.
In the Jest Docs I can only find assertions for testing javaScript functions and can't find any methods for traversing and testing Virtual DOM or shadow DOM elements like the ones I have been using( see above)
https://jestjs.io/docs/en/jest-object
How do I see what assertions are available to shallow() and shallow.find() with my current setup?
You can find the Jest assertion methods here Jest assertion methods
You could also look at this library package https://www.npmjs.com/package/jest-enzyme
So I picked react-redux-universal-hot-example as a starter kit.
I want to make ajax calls to 3rd party API.
(I want to use OpenWeatherMap API)
I want to use axios and react-promise middleware.
The first part installation is easy:
npm install --save redux-promise
npm install --save axios
Then I need to apply redux-promise middleware ... I think it goes into create.js somehow.
So I have several questions (all specific to react-redux-universal-hot-example) :
Is it the right way to do 3rd party calls using axios with redux-promise or the kit already have another way to do ajax requests?
Is create.js the right place to add redux-promise middleware?
Also, is there a concise syntax to apply multiple middlewares at the same time?
I am not 100% sure if you want to use react-promise or redux-promise. I am assuming the redux version. Which yea that create.js file is the right place to add it. You import a middleware from redux-promise and then add it to the lost of middlewares on line 9
import promiseMiddleware from 'redux-promise';
const middleware = [createMiddleware(client), reduxRouterMiddleware, promiseMiddleware];
So to answer your questions:
1. I am not 100% sure if the starter kit has a what to fetch 3rd party data. However using axios with redux-promise is exactly what I do.
2. Yes, see above on how.
3. Yep and that starter kit is showing one way which is creating an array of middlewares and then using the new spread operator it feed them into the applyMiddleware function. Which is a curried function that will then accept the createStore function. This is shown in the create.js file on line 21. Which is what the finalCreateStore will be during production.
4. The way I have been using this is with redux-actions which create Flux Standard Actions So..
// actionCreator
import { createAction } from 'redux-actions';
import { FETCH_DATA } from '../constants; // a file that exports constants
const fetchData = createAction(FETCH_DATA);
// reducer
const reducer = (state, action) => {
switch(action.type) {
case FETCH_DATA:
return {
...state,
fetchedData: action.payload.data
};
default:
return state;
}
}
// then dispatch the promise and not an action
store.dispatch(fetchData(axios.get('some_route')));
Then redux-promise 'intercepts' the promise and will resolve it. Once the promise resolves the action is then re-dispatched with the results in the payload. With axios you will get back an object that had the data you want as a property of that object. Which is shown is in the reducer with action.payload.data
A project I am working on that has this as an example.
Please not the actions have been wrapped with the dispatch call so all I have to do is call the actionCreators directly to get the same result as dispatching. This is explained in redux docs on bindActionCreators.
actionCreator
reducer
Component is where I dispatch the action
Where I hook up the middleware <-- similar to your create.js file
Again by dispatching the promise redux-promise intercepts(my way of understanding) the promise, resolves it and then dispatches the same action again but with the results of the promise on the payload property of the action object.
I understand this question has been asked multiple times on various sites and forums however the context has mostly been jquery. In my case, I am not using jquery at all though I am using CakePHP 1.3 with prototype and scriptoculous. I am trying to make Ajax pagination work using default Js helper however every time I load the page, I get the error below in error console
Error: $(document).ready is not a function
Any idea what's wrong here.
It seems (after some googeling) that the syntax to use in prototype is document.observe('dom:loaded', fn);
http://www.prototypejs.org/api/document/observe
In prototype, I think you can use
document.observe("dom:loaded", function() {
// Do initialization here
});
for performing the initialization tasks.