Get the data from an object - javascript

I'm sending request response to app class via redux.
And I receive it in props as I can console.log(this.props.data);
But I get this nested array full of objects
I've tried
console.log(this.props.data[0].PromiseValue);
which results in undefined
[Promise]
0: Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
headers: {pragma: "no-cache", content-type: "application/json; charset=utf-8", cache-control: "public, max-age=14400", expires: "Mon, 01 Apr 2019 22:25:19 GMT"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""

Have you tried to bind to the "then" event of the promise? Something like this:
this.props.data[0].then(value => {
console.log(value);
});

Related

axios successful request but data is undefined

I'm uploading multiple files separately using axios.
This is the request(all the following code is inside an async function):
const proms = files.map(file => {
let formData = new FormData();
formData.append("file", file);
return axios.post(`/upload/${userId}`, formData)
});
proms will be an array of promises so I proceed to Promise.all it:
const res = await Promise.all(proms)
If I do console.log(res) it shows a successfull response from server as you can see here:
Array(3) [ {…}, {…}, {…} ]​
0: Object { data: {…}, status: 200, statusText: "OK", … }​​
config: Object { timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", … }​​
data: Object { fieldname: "file", originalname: "612_photo.jpg", encoding: "7bit", … }​​​
destination: ********************​​****
encoding: "7bit"​​​
fieldname: "file"​​​
filename: "/1648309550808-586868206.jpeg"​​​
mimetype: "image/jpeg"​​​
originalname: "612_photo.jpg"​​​
path: ********************​​****
size: 43267​​​
<prototype>: Object { … }​​
headers: Object { "content-length": "395", "content-type": "application/json; charset=utf-8" }​​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }​​
status: 200​​
statusText: "OK"​​
<prototype>: Object { … }​
1: Object { data: {…}, status: 200, statusText: "OK", … }​
2: Object { data: {…}, status: 200, statusText: "OK", … }​
length: 3​
<prototype>: Array []
But then when I do console.log(res.data) it is undefined. What is happening here?
your response(res) is An array so you cant access res.data ,try :
res.forEach(item=>{console.log(item.data)})

How to access a react component fiber in whatsapp web from chrome console?

I'm trying to develop a chrome extension that access the conversation of WhatsApp Web. I'm struggling to access the Conversation component state (component that I can see with the React developper tools)
When I try
document.querySelector("#main")['__reactFiber$lwbvlqgcvdi']
I get something like this
alternate: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div#main._1fqrG, …}
child: zu {tag: 0, key: '33619488273-1490436851#g.us', stateNode: null, elementType: ƒ, type: ƒ, …}
childLanes: 1
dependencies: null
elementType: "div"
firstEffect: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div._26lC3, …}
flags: 0
index: 0
key: null
lanes: 0
lastEffect: zu {tag: 1, key: null, stateNode: t, elementType: ƒ, type: ƒ, …}
memoizedProps: {id: 'main', className: '_1fqrG', style: {…}, children: {…}}
memoizedState: null
mode: 0
nextEffect: null
pendingProps: {id: 'main', className: '_1fqrG', style: {…}, children: {…}}
ref: e=> {…}
return: zu {tag: 10, key: null, elementType: {…}, type: {…}, stateNode: null, …}
sibling: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div, …}
stateNode: div#main._1fqrG
tag: 5
type: "div"
updateQueue: null
[[Prototype]]: Object
instead of the following result I get when using the React developer tools $r variable
context: {}
props: {setInterval: ƒ, clearInterval: ƒ, setTimeout: ƒ, clearTimeout: ƒ, requestAnimationFrame: ƒ, …}
refs: {}
state: {chat: g, msgCollection: u, focusCtx: {…}, showConversationPreview: false, animate: false, …}
updater: {isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_handleCloseChat: e=> {…}
_handleOpenChat: (e,t,a)=> {…}
_handleOpenChatId: 1
_msgCollectionChanged: (e,t,a,s)=> {…}
_newChatScrollInfo: (e,t)=> {…}
_openedChatInfo: {chat: g, renderedMsgsInfo: {…}, visibleMsgOrder: Array(11), clientHeight: 572}
_reactInternals: zu {tag: 1, key: null, stateNode: y, elementType: ƒ, type: ƒ, …}
_refContainer: {current: t.default}
_windowGainedFocus: ()=> {…}
_windowLostFocus: ()=> {…}
[[Prototype]]: m
document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].stateNodereturns the same element than document.querySelector("#main")['__reactFiber$lwbvlqgcvdi']
document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].return gives me the context provider wrapping the component
return.stateNode returns null
What do I miss?
I finally figured it out.
It was the great great great great grandparent of the #main element. (Element react developer tools gives me as the matching DOM element for the Conversation component)
Now I know that React developer tools can give the same matching DOM element for different components ^^'
Update
To access the state I was looking for I used the following code :
document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].return.return.return.return.return.return.stateNode.state
I really found this out of luck as I was crawling up the graph of object out of boredom / despaire / curiosity ^^'

Vuex is changing object parameter into a component

I have a login form and where the inputs (email & password) are bound. On clicking the button to submit the form, it prevents the default behaviour and uses the login method defined in the Login.vue; Scripts.
While consoling in Login.vue; Scripts; login method, the form data printed out the {email: 'email', password: 'password'} object (desired). Once it is passed to the action (await this.signIn(this.form)), it consoled out a Vue component all of the sudden. I don't understand why this happened and how can this be solved?
Login.vue Component
Form
<form #submit.prevent="login" method="POST">
<input
type="text"
v-model="form.email"
/>
<input
type="password"
v-model="form.password"
/>
<button class="btn btn-primary">Login</button>
</form>
Scripts
<script>
import { mapActions } from 'vuex'
export default {
data() {
return {
form: {
email: '',
password: '',
},
}
},
computed: {
...mapActions('auth', ['signIn']),
},
methods: {
async login() {
/***************************************
* *
* Print out the form data object *
* *
****************************************/
console.log(this.form)
await this.signIn(this.form)
},
},
}
</script>
Vuex - Auth Module
export const actions = {
signIn({ dispatch, commit }, form) {
/***************************************************************
* *
* Print out a Vue component instead of the passed object *
* *
****************************************************************/
console.log(form)
Auth.signInWithEmailAndPassword(form.email, form.password)
.then(user => {
commit('SET_AUTHENTICATED', true)
commit('SET_USER', user.user)
this.$router.push('/')
})
.catch(err => {
console.log(err)
})
},
}
Console logged content
VueComponent {_uid: 4, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
$attrs: (...)
$children: []
$createElement: ƒ (a, b, c, d)
$el: div
$listeners: (...)
$options: {parent: VueComponent, _parentVnode: VNode, propsData: undefined, _parentListeners: undefined, _renderChildren: undefined, …}
$parent: VueComponent {_uid: 3, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
$refs: {}
$root: Vue {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
$scopedSlots: {$stable: true, $key: undefined, $hasNormal: false}
$slots: {}
$store: Store {_committing: false, _actions: {…}, _actionSubscribers: Array(1), _mutations: {…}, _wrappedGetters: {…}, …}
$vnode: VNode {tag: "vue-component-4", data: {…}, children: undefined, text: undefined, elm: div, …}
form: (...)
login: ƒ ()
signIn: (...)
__VUE_DEVTOOLS_UID__: "1:4"
_c: ƒ (a, b, c, d)
_computedWatchers: {signIn: Watcher}
_data: {__ob__: Observer}
_directInactive: false
_events: {hook:beforeDestroy: Array(1)}
_hasHookEvent: true
_inactive: null
_isBeingDestroyed: false
_isDestroyed: false
_isMounted: true
_isVue: true
_renderProxy: Proxy {_uid: 4, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
_routerRoot: Vue {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
_self: VueComponent {_uid: 4, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
_staticTrees: null
_uid: 4
_vnode: VNode {tag: "div", data: undefined, children: Array(2), text: undefined, elm: div, …}
_watcher: Watcher {vm: VueComponent, deep: false, user: false, lazy: false, sync: false, …}
_watchers: (2) [Watcher, Watcher]
$data: (...)
$isServer: (...)
$props: (...)
$route: (...)
$router: (...)
$ssrContext: (...)
get $attrs: ƒ reactiveGetter()
set $attrs: ƒ reactiveSetter(newVal)
get $listeners: ƒ reactiveGetter()
set $listeners: ƒ reactiveSetter(newVal)
get form: ƒ proxyGetter()
set form: ƒ proxySetter(val)
__proto__: Vue
As Sumurai8 mentioned, I only need to put the ...mapActions('auth', ['signIn']) in methods and not in computed.
methods: {
...mapActions('auth', ['signIn']),
async login() {
console.log(this.form)
await this.signIn(this.form)
},
},

Fill Dropdown option values from API MVC C#

I have a API that is called when dropdown value changes. It returns JSON results and I would like to update another dropdown from those JSON results but I keep getting an error in my Jquery
Razor View Page
<div class="form-group">
#Html.LabelFor(model => model.CustomerProfile.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerProfile.Country, Model.CountryList, htmlAttributes: new { #id = "profileCountry", #class = "form-control col-md-2" , #onchange = "FillState()" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerProfile.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerProfile.State, new SelectList(Enumerable.Empty<SelectListItem>(), "StateFullName", "StateFullName"),
"Select State",
htmlAttributes: new { #id = "profileState", #class = "form-control col-md-2" })
</div>
</div>
Jquery Script
<script>
function FillState() {
var countryParam = $('#profileCountry').val();
$.ajax({
url: '/api/CountryToState/FillState',
type: "GET",
dataType: "JSON",
data: { country: countryParam},
success: function (states) {
$("#profileState").html(""); // clear before appending new list
$.each(states, function (i, statetest) {
$("#profileState").append(
$('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
});
}
});
}
</script>
API Code
[System.Web.Http.HttpGet]
public ActionResult FillState(string country)
{
var states = _context.CountryToState.Where(c => c.CountryName == country);
return new JsonResult()
{
Data = states,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
CountryToState Model
public class CountryToState
{
[Column("lngStateID")]
[Key]
public Int32 StateID { get; set; }
[Column("strCountry")]
public string CountryName { get; set; }
[Column("strStateFullName")]
public string StateFullName { get; set; }
}
It keeps giving me an error on Cannot read property 'StateFullName' of null. states returned in success function has 36 rows with StateFullName of every row. Why it is null. How can I fix this. I want value and text to be StateFullName in the drop down.
I do not understand the .each function properly
Console.Log(states) show the following:
ContentEncoding: null, ContentType: null, Data: Array(36), JsonRequestBehavior: 0, MaxJsonLength: null, …}
ContentEncoding: null
ContentType: null
Data: (36) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
JsonRequestBehavior: 0
MaxJsonLength: null
RecursionLimit: null
__proto__: Object
I Reviewed your code and I think the error originates from ajax success function
$.ajax({
url: '/api/CountryToState/FillState',
type: "GET",
dataType: "JSON",
data: { country: countryParam},
success: function (states) {
$("#profileState").html(""); // clear before appending new list
$.each(states, function (i, statetest) {
$("#profileState").append(
$('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
});
}
});
In the code above I think that state parameter in success callback has such a structure:
{
ContentEncoding: ...
ContentEncoding: ...
ContentType: ...
Data: (36) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
JsonRequestBehavior: ...
MaxJsonLength: ...
RecursionLimit: ...
}
so you need to make a loop in states.Data instead of states :
$.each(states.Data, function (i, statetest) {
$("#profileState").append(
$('<option></option>').val(statetest.StateFullName).html(statetest.StateFullName));
});

setState doesn't set values

We got a ReactJS frontend delivered for our school project. We have to make a Laravel backend for it. I'm using an API to fetch the dashboard layout from the database. The current frontend makes use of this variable:
const originalLayouts = getFromLS("layouts") || [];
To set the state from the local storage with this function:
function getFromLS(key) {
let ls = {};
if (global.localStorage) {
try {
ls = JSON.parse(global.localStorage.getItem("rgl-8")) || {};
} catch (e) {
/*Ignore*/
}
}
return ls[key];
}
Where the states are set:
this.state = {
items: originalLayouts.map(function(i, key, list) {
return {
i: originalLayouts[key].i,
x: originalLayouts[key].x,
y: originalLayouts[key].y,
w: originalLayouts[key].w,
h: originalLayouts[key].h,
widget: originalLayouts[key].widget,
minW: originalLayouts[key].minW,
minH: originalLayouts[key].minH,
maxH: originalLayouts[key].maxH
};
}),
selectedOption: '',
newCounter: originalLayouts.length
};
To fetch the data from the database and put the data into the items state I made this function:
loadData = () => {
let dashboardId = 1;
return axios
.get('api/dashboards/' + dashboardId)
.then(result => {
console.log(result);
this.setState({
originalLayouts: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
console.log(result.data);
})
.catch(error => {
console.error('error: ', error);
})
};
And I call this function in componentDidMount:
componentDidMount() {
this.loadData();
}
When I console log result it shows me this:
data: Array(2), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: (2) [{…}, {…}]
headers: {date: "Tue, 23 Oct 2018 08:18:41 +0000, Tue, 23 Oct 2018 08:18:41 GMT", host: "127.0.0.1:8000", x-powered-by: "PHP/7.2.3", x-ratelimit-remaining: "58", content-type: "application/json", …}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object
And when I console log result.data I get:
(2) [{…}, {…}]
0: {id: 1, dashboardId: 1, w: 2, h: 5, x: 0, …}
1: {id: 2, dashboardId: 1, w: 2, h: 1, x: 0, …}
length: 2
__proto__: Array(0)
Why is originalLayouts not set with the data from the arrays? Is this because I also have a dashboardId and id in my arrays? I also thought it could be something with setting the states because it makes use of the originalLayouts veriable. Or am I still missing something in my function? I'm not very experienced with React so any help is useful.
Update:
I changed:
this.setState({
originalLayouts: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
to:
this.setState({
items: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
This gives me this error:
Uncaught Error: ReactGridLayout: ReactGridLayout.children[0].static must be a boolean!
So that probably means I'm not setting the properties properly now.
Update 2:
In my database the properties moved and static were saved as 0 instead of false. So I changed those properties to false but I still got the same error:
ReactGridLayout: ReactGridLayout.children[0].static must be a boolean!
In your loadData(), you are setting the state of "originalLayouts" but your key in your initial state is "items". Have you tried to do this ?
this.setState({
items: result.data, // Here put items instead of originalLayouts
selectedOption: '',
newCounter: originalLayouts.length
});
Then you can call this.state.items to get your result.data

Categories