How to replace 'useResult' in graphql with vue and apolo? - javascript

I have to replace this useResult that is fetching data from graphql
const locationOptions = useResult(
result,
[],
({ getLocations }): Option[] => formatOptions(getLocations)
)
and I want to change it for a computed function like
const locationOptions = computed(() => result.value.getLocations ?? [])
I was trying to use a watch to run the function but it seems not to be working
watch(locationOptions, () => {
formatOptions(locationOptions.value)
})
any suggestions?

You can use the format function already in the computed function:
const locationOptions = computed(() => {
return result.value?.getLocations ? formatOptions(result.value.getLocations) || []
})

Related

how can I fetch random data by product id or slug in a single component in useQuery? its showing the same data for all component

this is my code.
const fetchCartItem = async () => {
if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(false);if (data?.product === undefined) {return {};}else {return data?.product ? data?.product : {};}}};
const{isLoading: itemLoading,refetch: cartRefetch,data: cart,} = useQuery(["cart"], () => fetchCartItem());
If you want to fetch data according to your object ID in useQuery then you just need to pass the ID before calling the function. For ex:
const { isLoading: itemLoading, refetch: cartRefetch, data: cart} = useQuery(["cart", item?.ProductID], () => fetchCartItem());

How do I use forEach to push into an array with React useState?

I'm trying to use the same code below in React. I've tried a couple ways but it doesn't work the same way.
working old code (not react code)
const array = []
res = await getData()
res.data.forEach(item) => {
array.push({
...item,
isSelected: false,
id: getItemId(item.id)
})
not working new code (React)
const [array, setArray] = useState([])
const fetchItems = useCallback(async () => {
res = await getData()
const newData = res.data.forEach(item) => {
return [{...item, isSelected: false, id: getItemId(item.id) }]
})
setArray(newData)
}, [])
fetchItems()
console.log(array)
Is there a clean way to write this the same way it was done in the working code? Preferably without using push
try
const fetchItems = useCallback(async () => {
res = await getData()
const tempArr = res.data.map(item => ({...item, isSelected: false, id:
getItemId(item.id) }))
setArray(tempArr)
}, [setArray, getData, getItemId])
but make sure your functions getData, getItemId wont change by wrapping them with useCallback as well or avoid using useCallback.
In this change:
const newData = res.data.forEach(item) => {
What are you expecting forEach() to return and why? Taking a step back... You already have working code, so just use your known working code. Since the React component declares an array variable already, the only change you need to make is to rename your local variable:
const newArray = []
res = await getData()
res.data.forEach(item) => {
newArray.push({
...item,
isSelected: false,
id: getItemId(item.id)
})
})
Then just update state to your new array:
setArray(newArray);
Here is an approach:
const newData = res.data.map((item)=>{
return {
...item,
isSelected: false,
id: getItemId(item.id)
}
})
setArray(newData)
This will modify the value of the state .
Replace your Array.forEach to use Array.map. Because Array.forEach returns undefined but you expecting to have a new array.
I suppose that you should use useEffect rather than useCallback when fetching/editing data inside the component. In react you can write like this;
async function handleFetch() {
const res = await getData();
const newData = res.data.map((item) => {
return [{ ...item, isSelected: false, id: item.id }];
});
setArray(newData);
}
useEffect(() => {
handleFetch();
}, []);
to mock data I wrote this ;
function getData() {
return { data: [{ isSelected: true, id: 1 }] };
}
And you can check out stackblitz link

Empty return when adding an object to_.transform in Lodash

I'm using Lodash to do some work on our object. So I had a little problem that I can't solve.
I'm trying to add the result of a query, in the _.transform array. But without success.
The return is empty.
I did some tests using the console.log and the value is shown normally.
const result = _.transform(data.items, async (r: any, v: any) => {
let data = await Cliente.query().where('id', '=', v.codiPsv).orderBy('validade', 'asc').first()
if (data){
console.log(data.serialize()) --> Show object
r.push(data.serialize())
console.log(0)
}
})
console.log(result) --> empty
Resolved
const cods = _.map(data.items, 'codiPsv')
const items = await Cliente.query().whereIn('id', cods).orderBy('validade', 'desc')
const itemsSerelialize = items.map((item) => item.serialize())
const result = _.transform(data.items, async (r: any, v: any) => {
const item = _.filter(itemsSerelialize, {'id':v.codiPsv}).slice(-1).pop()
if ( !_.isUndefined( item )) {
r.push(item)
} else {
console.log(v)
r.push({'local': 'Indisponível', ...v})
}
})

Unable to access nested object from JSON data

I have the following function component in React:
function GetData() {
const [randomDataJSON, setRandomDataJSON] = useState('');
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomDataJSON(JSON.stringify(userData, null, 2));
})
.catch((err) => console.error(err));
};
return (
<div>
<h3>GetData Component</h3>
<pre>{randomDataJSON[0].name.first}</pre>
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;
The JSON data from the API is as follow:
[
{
"gender": "female",
"name": {
"title": "Miss",
"first": "Barbara",
"last": "Sullivan"
},
...
I would like to access and display the first name of the JSON data from the API by using {randomDataJSON[0].name.first in the <pre> tag. However, I keep getting the following error message: TypeError: Cannot read properties of undefined (reading 'name')
You are setting json string to randomDataJSON state variable, and trying use JSON string as an object. You can try to console.log(randomDataJSON) to confirm my suspicions.
I think you should not convert your data object to json in first place, so setRandomDataJSON(JSON.stringify(userData, null, 2)); will be setRandomDataJSON(userData);
function GetData() {
const [randomData, setRandomData] = useState('');
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomData(userData, null, 2);
})
.catch((err) => console.error(err));
};
return (
<div>
<h3>GetData Component</h3>
<pre>{randomData[0].name.first}</pre>
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;
At the time the page loads axios wouldn't have ran to request the array so randomDataJSON is a string at that time. You could do
const [randomDataJSON, setRandomDataJSON] = useState([]);
Above you set it to an empty array then check if it has length
<pre>{randomDataJSON.length > 0 && randomDataJSON[0].name.first}</pre>
Thank you very much to everyone pointing me in the right direction. My new code is as follow. My problem was I didn't know React doesn't allow you to render Javascript Object. To fix this, I just use the map() method to map through the data and display the properties in the object.
function GetData() {
const [randomDataJSON, setRandomDataJSON] = useState([]);
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomDataJSON(userData);
})
.catch((err) => console.error(err));
};
console.log('It is an', typeof randomDataJSON);
console.log('randomDataJSON is ', randomDataJSON);
return (
<div>
<h3>GetData Component</h3>
{randomDataJSON.map((data) => {
return <p>{data.name.first}</p>;
})}
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;

React useCallback - I can't update my function

I want to update my callback function:
const getSchema = React.useCallback(
() => {
const schema = twSchema(
labels,
isInitialWarehouseActive ? initialWarehouse.id : undefined,
operationTypeDisabled ? initialWarehouse.operation_type : undefined
);
schema.addValidator((model, _schema) => {
if (model.dateRangeMode && (!model.timeRangeMode || model.hasRampHours) && !model.dateInpu.to) {
_schema.setModelError('dateInput.to', labels.fieldIsRequired);
...
...
});
return schema;
},
[initialStore]
);
where twSchema:
const twSchema = (labels, initialStoreId, storeOperationType) => new Schema({...
And use case of my getSchema:
<Form
key="time-window-form"
ctx="time-window-form"
eventsEmitter={eventsEmitter}
model={model}
onError={onError}
onSubmit={(data) => {
...
}).then(() => {
...
})
.catch(hint => displayMessageAndHighlightValidatedComponent(hint));
}}
schema={getSchema()}
>
I use this value (getSchema) to my form (I have to set schema to my form).
Depending on the error that can occur I'd like to add some validator to my schema BUT I CAN'T:
const displayMessageAndHighlightValidatedComponent = (hint) => {
getSchema().addValidator((model, schema) => {
//this code is not executed!!!
console.log(schema);
console.log('SCHEMA');
schema.setModelError('dateInputField', labels.createNextTimeWindow);
});
return onFailed();
};
The question is why? Why I can't update my object/function? I have to remove useCallback to be able to add validator dynamically...

Categories

Resources