I have the following code:
const [intrebari, setIntrebari] = useState([])
useEffect(() => {
let idVar = localStorage.getItem('idVarianta');
idVar = JSON.parse(idVar)
axios({
method: "POST",
data: {
idVarianta: idVar,
},
withCredentials: true,
url: "http://localhost:4000/getIntrebari",
}).then((res) => {
console.log(res)
const data = res.data;
setIntrebari(data);
console.log('Data has been recieved');
});
}, [])
which is returning me this:
How can I access the data? If I try intrebari[0].intrebare it gives me "Cannot access property intrebare of type undefined". Any idea? I tried also to console log intrebari[0] and it's displaying the first element, but when i'm trying to access intrebari[0].intrebare it gives me the error described above.
Thanks
Instead of setIntrebari(data), try setIntrebari(res).
Solved it by adding this. The problem was that the component was rendering before the data was fetching.
function getIntrebare() {
if (intrebari.length !== 0) {
return intrebari[questionIndex].intrebare;
}
return "";
}
Related
I'm working on react native project, and i'm calling API and extracting data from it , the data is succesfully extracted but I want to take arguments from the extracted data and I did'nt know how
This is the code for fetching api :
Axios({
url: '/Authentification',
method: 'get',
baseURL: 'http://smart.netrostercloud.com/api',
transformRequest: [
function (data, headers) {
return data;
},
],
transformResponse: [
function (data) {
// console.log(data);
setData3(data);
},
],
headers: {
Authorization: 'Basic UxvwJc1GWjkOCyZoIHGuCD05gDUB72sqrgK30FgILho=',
},
});
console.log(data3);
I've used data3 to extract the data in my main function so it can be visible.
This is the data :
I want to take CompanyCode,UserName,Password,FirstName and LastName
Firstly : axios its n asynchronous function, so its return a promise,
Actually i dont prefere use this patern in simple api call l, but its good way if you know this concept and use oop like create instance of axios to reusable and cancel connectiin when component will unmount.
Fot this i prefere use this way
Const getUserData= async () =>{
try {
Const {data} = await axios.get(baseurl+route, headers , options)
data & & SetData({username:data. User. Username,........... } )
Dosomthing...
}
Catch(error) {
Dosomthing...
}
Before you storing data into data3 you need to stringify the data like this setData3(JSON.stringify(data));
and then try this:
if (data3) {
const COMP_NAME = data?.user?.CompanyCode;
const USER_NAME = data?.user?.UserName;
CONST FIRST_NAME = data?.user?.FirstName;
CONST LAST_NAME = data?.user?.LastName;
}
I have the next hook in my react js application:
const {
data,
loading
} = fetchData(info)({
variables: {
id: myId,
},
fetchPolicy: 'no-cache',
});
//
const fetchData = (info) => {
if (a > 1) {
return useGetCars;
}
return useGetColors;
};
The issue appear in the first render when the myId is empty, but it is required. Due this fact i get an error from the server.
Question: How to create a condition for the hook above to be able to run it only when the myId is not empty?
Use the effect hook:
useEffect(() => {
if (myId) {
fetchData() // after this, you can set the required states.
}
}, [myId])
I am fetching an array of objects in the state, and I am trying to add a property to each of these objects.
The problem is I can see my property being added to each of the objects but when I mapping through all these objects and trying to console.log it I'm getting undefined
Adding a property
addFavourites() {
let data = this.state.data.map((e) => {
e.favourite = false;
return e;
});
return data;
}
state = {
data: []
}
addFavourites's called here:
getItem = () => {
this.service
.mergeData()
.then((body) => {
this.setState({
data: body
},
() => {
this.addFavourites();
},
() => {
this.dataToFilter();
});
});
}
componentDidMount(){
this.getItem();
}
In render function I see all my objects including favourite
console.log(data.map((e) => e));
But this gives an array of undefined
console.log(data.map((e) => e.favourite));
How can I solve this?
First, welcome! You should have probably made it more clear that this question is about React.
Now to the answer, every state modification would be made using setState, so your addFavourites function should be like this:
addFavourites() {
let data = this.state.data.map((e) => {
e.favourite = false;
return e;
});
this.setState({ data: data });
}
Using redux-api-middleware which works similarly to axios and jquery.ajax, I passed a formData which is a mixture of an image and other form values as you can see on this image:
The problem I have is that after successfully calling the API via a POST request, the PHP $_POST object is null though there was an actual POST request happening. This is my code snippet:
import { CALL_API } from "redux-api-middleware";
export function createTestAnnouncement(data) {
return (dispatch, getState) => {
const { auth: { oauthToken, oauthTokenSecret } } = getState();
const formData = new FormData();
Object.entries(data).forEach(([key, value]) => {
if (key === 'image') {
formData.append(key, value);
} else {
formData.set(key, value);
}
});
return dispatch({
[CALL_API]: {
endpoint: "/api/test-announcements",
method: "POST",
headers: {
'xoauthtoken': oauthToken,
'xoauthtokensecret': oauthTokenSecret,
},
body: formData,
types: [CREATE_TEST_ANNOUNCEMENTS, CREATE_TEST_ANNOUNCEMENTS_SUCCESS, CREATE_TEST_ANNOUNCEMENTS_FAILURE]
}
})
}
}
How will be able to get values from the $_POST object? Did I use the FormData object correctly?
EDIT: My Controller is just this, PS: I am sure this working because this is working on a plain application/json request
use api\controllers\BaseController;
use model\Operations\TestAnnouncements\TestAnnouncementOperation;
use model\DB\TestAnnouncement;
class IndexController extends BaseController
public function actionCreate()
{
var_dump($_POST);
// Commented this out because the payload is not JSON
// $request = \Yii::app()->request;
// $op = new TestAnnouncementOperation();
// $op->topic = $request->getJSON('topic');
...
}
...
I always get a NULL on my var_dump. While using postman and passing form-data on the body generates me a value on my $_POST.
you can check if the variable is set or not using...
if(!isset($_POST["ur_varible_name_from_html_form"]))
{
echo "error";
}
You can see redux-api-middleware repo on github, issues #125. They already have resolved and given example [CALL_API] and [RSAA] with from data.
Expected query string:
http://fqdn/page?categoryID=1&categoryID=2
Axios get request:
fetchNumbers () {
return axios.get(globalConfig.CATS_URL, {
params: {
...(this.category ? { categoryId: this.category } : {})
}
})
.then((resp) => {
// console.log(resp)
})
.catch((err) => {
console.log(err)
})
}
As you can see, it works perfectly with just 1 value for 1 parameter, but if i wanted to make multiple values - it doesn't work, i've tried to use an array:
...(this.category ? { categoryId: [1, 2] } : {})
But it returns this way:
http://fqdn/page?categoryID[]=1&categoryID[]=2
So it just not working. Had a look at this issue: Passing an object with a parameter with multiple values as a query string in a GET using axios
But can't figure out, how he solved this problem.
You can use Axios's paramsSerializer to customize the serialization of parameters in the request.
Note that URLSearchParams serializes array data the way you're expecting:
const searchParams = new URLSearchParams();
searchParams.append('foo', 1);
searchParams.append('foo', 2);
console.log(searchParams.toString()); // foo=1&foo=2
So you could use that class in paramsSerializer as follows:
// my-axios.js
export default axios.create({
paramsSerializer(params) {
const searchParams = new URLSearchParams();
for (const key of Object.keys(params)) {
const param = params[key];
if (Array.isArray(param)) {
for (const p of param) {
searchParams.append(key, p);
}
} else {
searchParams.append(key, param);
}
}
return searchParams.toString();
}
});
// Foo.vue
import axios from './my-axios.js';
export default {
methods: {
async send() {
const { data } = await axios({
url: '//httpbin.org/get',
params: {
categoryId: [1, 2, 3]
}
});
// ...
}
}
}
demo
This is not an axios related issue. It depends on whether your backend service is able to understand query params in this fashion(seems to be framework dependent). From your question, I think it is not working when queryParams like following are sent
?categoryID[]=1&categoryID[]=2
and it expects
?categoryID = 1,2
What you can do is transform array to such string before passing it to params in axios. Update the following piece in your code and it should solve your problem.
...(this.category ? { categoryId: this.category.join(',') } : {})
Take a look at following thread
How to pass an array within a query string?