I have two pieces of code, the Front-end in React and the Bakc-end in Laravel, the problem is im calling the API to get an array of a SQL join but in the useEffect React Hook it doest get the info, but if i make a button to get it works, i don't know why the useEffect Hook isn't working properly
I partially solved the question by treating the response as an array but if you are sending more than 1 thing i still dont know what to do
I have this pieces of code
Laravel:
public function show($id)
{
$returned = response('El lote solicitado no existe', Response::HTTP_BAD_REQUEST);
$lote = DB::table('lotes')
->leftjoin('articulos', 'lotes.idArticulo', '=', 'articulos.id')
->select('lotes.idLote', 'lotes.idArticulo', 'lotes.cantidad', 'lotes.consumoPreferente', 'lotes.observaciones', 'articulos.descripcion')
->where('lotes.id', $id)
->get();
if($lote){
$returned = response($lote, Response::HTTP_OK);
}
return $returned;
}
React:
const [lote, setLote] = useState([])
useEffect(() => {
document.title = `Lote ${id}`
getLote()
}, [])
const { id } = useParams()
const getLote = async () => {
try {
const response = await axios.get(`${endpoint}/lote/${id}`)
setLote(response.data)
} catch (e) {
console.log(`Error ${e}`)
}
}
The problem is that lote isn't setting in the useEffect hook, but if i call the getLote function outside of it works.
Another issue is that if i change the laravel part to this works properly on the useEffect call:
I think the key is here, if i use the 'findOrFail' it works properly but if make a SQL query it doesn't, but if im using the async - await it should wait, rigth?
$lote = Lote::findOrFail($id);
if($lote ){
$returned = response($lote , Response::HTTP_OK);
}
return $returned;
Also to mention im ussing axios to make the calls, could it be the problem too?
Do you know what could be happening?
The first thing you need to do is to make sure that id is already defined in useEffect, so you need to re-write useEffect like this:
useEffect(() => {
if(!id) {
return;
}
document.title = `Lote ${id}`
getLote()
}, [id]);
also, I would recommend putting function in useCallback
const getLote = useCallback(async () => {
try {
const response = await axios.get(`${endpoint}/lote/${id}`)
setLote(response.data)
} catch (e) {
console.log(`Error ${e}`)
}
}, [id]);
It is crucial to add relevant dependencies in deps array.
I solved the question by doing an intermediate step
If the data that is being sended is only one object in the array
const [lote, setLote] = useState([])
useEffect(() => {
document.title = `Lote ${id}`
getLote()
}, [])
const { id } = useParams()
const getLote = async () => {
try {
const response = await axios.get(`${endpoint}/lote/${id}`)
setLote(response.data[0])
} catch (e) {
console.log(`Error ${e}`)
}
}
If the data that is being sended are more than one object in the array
const [lote, setLote] = useState([])
useEffect(() => {
document.title = `Lote ${id}`
getLote()
}, [])
const { id } = useParams()
const getLote = async () => {
try {
const response = await axios.get(`${endpoint}/lote/${id}`)
let newLote = response.data
setLote(newLote)
} catch (e) {
console.log(`Error ${e}`)
}
}
I don't know why this happens but this solution worked for me
Related
I'm using Angular with PHP and trying to post an object. Request status is 200, but $_POST array is empty. Data I'm sending is a valid JSON Object.
sendTweet(){
if(!this.username || !this.tweet){
alert("Enter username or tweet");
return;
}
const newTweet:Tweet = {
username: this.username,
tweet: this.tweet
}
//Call Service
this.testService.postTweet(newTweet).subscribe((response)=>{console.log(response)},
(err:any)=>{
console.log(err.message);
});
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
postTweet(tweet:Tweet):Observable<Tweet>{
const url = `${this.apiUrl}/?page=submit&action=add`;
return this.http.post<Tweet>(url,tweet, httpOptions);
}
PHP:
if (isset($_POST['tweet'])&&isset($_POST['username'])) {
//Sending tweet to the db
} else{
print_r($_POST);
}
i dont know if its a backend problem with php but in my project i have it a little bit diferent (i am using .net core for backend)
for example in my project:
//service component WebScrapLinkService
get(): Observable<Any[]> {
return this.http.get<Any[]>(this.url)
.pipe(map(res => res));
}
//main component
getRegisters() {
this.getProductsSub = this.crudService.get()
.subscribe(data => {
this.registers = data;
})
}
//variables
public registers: Array<object> = [];
//the service goes in the constructor
private crudService: WebScrapLinkService
this works fine for me, i hope it is useful for you
It was just me not knowing that in PHP you have to parse HTTP_RAW_POST_DATA in order to get the data.
I've been trying to load all of my data when the time I log in. Currently, I've only managed to display data through the console through vuex file. I just want to achieve this because wherever it loads all data when login, it will easier for me to call every function on every page.
I think the first step is to display it on vue devtools?
This is what I've tried.
I have this file on my "./store/modules/currentUser.js"
import axios from "axios";
const state = {
};
const getters = {};
const actions = {
loadEmployee({}){
axios.post(BASE_URL + '/transportation/driver/autoComplete').then(response => {
console.log(response.data); // how to pass result to devtools?
});
}
};
const mutations = {};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
Login.vue
<script>
export default {
data () {
return {
listdata:[]
}
},
methods: {
login() {
this.$store.dispatch('currentUser/loadEmployee', this.listdata);
}
}
}
</script>
This is my vuedevtools looks like
And I want to fetch all data on listdata array vue devtools
If you are using vuex, you should probably load state in dev tools.
However, your issue is caused by not having a mutation, so you never update the state.
import axios from "axios";
const state = {
transansportDrivers: []
};
const getters = {};
const actions = {
loadEmployee({}){
axios.post(BASE_URL + '/transportation/driver/autoComplete').then(response => {
commit('setTransportDrivers', response.data)
});
}
};
const mutations = {
setTransportDrivers: (state, drivers) => {
state.transansportDrivers= drivers;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
I want to send POST data from NodeJS server (localhost:4000) to PHP symfony server (localhost:8000)
But every time when I'm trying to send it, I got always same result => empty array.
Here is my code:
NodeJS
var data = {
method: "disconnectFromGame",
};
var querystring = require("querystring");
var qs = querystring.stringify(data);
var qslength = qs.length;
var options = {
hostname: "http://localhost:8000",
port: 80,
path: "/game/api",
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': qslength
}
};
var buffer = "";
var req = http.request(options, function (res) {
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function () {
console.log(buffer);
});
});
req.write(qs);
req.end();
It works fine, debugger stop me at the specific breakpoint, so communication is OK, but $request has always empty parameters..
PHP Symfony 5
public function engineApi(Request $request) {
$user = $this->getUser();
if(!$user) {
return $this->redirectToRoute("app_login");
}
if (!$request->isXMLHttpRequest()) {
return $this->redirectToRoute("app_homepage_show");
}
$entityManager = $this->getDoctrine()->getManager();
$data = $request->request->all();
$api = new Api($data, $user, $entityManager);
return $api->processMethod();
}
Your script works :
How do you get the picture of your dump ? Because I think, this is where you made a mistake.
When you execute the NodeJs script, did you get a response from the Symfony server in your console ? Because if you put a dump() in your Symfony, you should have something like this (which is the raw view of html response with dump data from Symfony) :
So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()
Hi my jQuery callback function does not work.
Competitor = {
addCompetitorForSave: function($data) {
$.post('/competition/add', $data , function($json) {
}, 'json');
return $json; // I need to return json data .
}
}
after this I need to do next .
var data = $('someForm').serialize();
var $json = Competition.addCompetitorForSave(data);
Thanks a lot.
The post completes asynchronously but the alert runs synchronously. Hence the qa value hasn't been set yet. Instead of return a value here you need to pass an additional callback into addCompetitorForSave.
addCompetitorForSave: function($data, callback) {
var qa = 0;
$.post('/competition/add', $data , function($json) {
callback($json);
}, 'json');
}
var obj = ...;
obj.addCompetitorForSave(theData, function(qa) {
alert(qa);
});
The alert is called before the post has had a chance to complete. Put the alert inside the callback.
try:
addCompetitorForSave: function($data) {
var qa = 0;
$.post('/competition/add', $data , function($json) {
qa = $json; //this does not work
alert(qa); //getting 0;
}, 'json');
return qa;
}