When I did the following:
import { useGetPostQuery } from "./store/postApi";
export function App() {
const { data, isLoading, isFetching, isError, error } = useGetPostQuery(1);
if (isError)
return (
<div>
{error.status}
<br />
{error.data}
</div>
);
if (isLoading) return <div>loading...</div>;
return <div className={isFetching ? "posts--disabled" : ""}>{data}</div>;
}
I received an error:
PARSING_ERROR
HELLO WORLD
Basically, I just want to return the string HELLO WORLD from the server. How should I avoid the parsing error?
A Code Sandbox for the example can be found here.
I guess it expects a JSON response.
My PHP script:
echo json_encode(array("data"=>file_get_contents("data".$_GET["id"].".txt")));
Related
I am using antd Select and react hook form via 'Controller'. I am populating the Select options from a fetched data with structure;
{
{
"id": "232342",
"term": "hello"
}
{
"id": "232342",
"term": "hello"
}
}
the Select component properly displays the term for selection. However, i want to retrieve both the 'id'and 'term' of the selected and use it to populate another json object.
getValues(" ") retrieves the 'id' only. How do i retrieve and access both the 'id' and 'term'.
Here is a portion of code:
import React from 'react'
import { useForm, Controller } from 'react-hook-form'
import { Select } from 'antd'
const { Option } = Select
export default function PatientRegistrationForm({ options }) {
const { register, handleSubmit, getValues, control, formState: { errors } } = useForm({
defaultValues: {
customer: "",
}
})
const children = []
for (const {id, pt: {term}} of options){
children.push(<Option key={id}>{term}</Option>)
}
// Define the retrieved values from the form
const retrievedID = getValues("customer")
// Use the retreived values to populate this object
const customer = {
customerId = retrievedID
customerName = "nothing happens here"
},
return (
<div className="">
<form onSubmit={handleSubmit(onSubmit)} className="">
<section>
<Controller
control={control}
name="customer"
render={({ field }) => (
<Select {...field} defaultValue=""
bordered={true}
filterOption={true}
className="form-control"
>
{ children }
</Select>
)}
/>
</section>
</form>
</div>
);
}
Thanks in advance for your help.
You have to retrieve the option manually using something like:
const retrievedID = getValues("customer")
const retrievedOption = options.find(option => option.id === retrievedID)
const customer = {
customerId: retrievedID,
customerName: retrievedOption.term
}
thank you #sgarcia.dev for your answer. I know its been a while but i want to put it out here incase it helps someone else. It turns out it had little to do with react hook form. Ant design select component has a prop 'labelInValue' which returns an object containing both the label and value.
I am trying to create a delete functionality in my application which seems to be deleting the object from the backend just fine, but not in the frontend.
Here is how I structured my project:
in actions/deleteJournal.js
export const deleteJournal = (journal) => {
return dispatch => {
fetch(`http://localhost:3001/journals/${journal.id}` , {
method: "DELETE" })
.then(resp => resp.json())
.then(journal => { dispatch({ type: "DELETE_JOURNAL", journal })
})
}
}
in reducers/journalsReducer.js
const initialState = {
journals: [],
loading: true
}
const journalsReducer = (state=initialState, action) => {
switch(action.type) {
case "LOADING":
return {
...state,
loading: true
}
case "SET_JOURNALS":
return {
...state,
loading: false,
journals: action.journals
}
case "ADD_JOURNAL":
return {
...state,
journals: [...state.journals, action.journal],
}
case 'DELETE_JOURNAL':
return {
journals: state.journals.filter(todo => todo.id !== action.id),
...state
}
default:
return state;
}
}
export default journalsReducer
in components/List.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Journal from './Journal'
import { deleteJournal } from '../actions/getJournals'
class ListFiltered extends Component {
render() {
const journals = this.props.journals.map( journal => journal.locationId === this.props.locationId && <Journal key={journal.id} title={journal.title} content={journal.content} id={journal.id} deleteJournal={this.props.deleteJournal} />)
return (
<div>
{journals}
<p></p>
</div>
)
}
}
const mapStateToProps = state => {
return {
journals: state.journals
}
}
export default connect(mapStateToProps, {deleteJournal})(ListFiltered)
in components/Journal.js
class Journal extends Component {
render() {
const { id, title, content } = this.props;
return (
<div>
<ul>
<li>
<h3>{ title } </h3>
<p> { content }</p> <button onClick={() => this.props.deleteJournal(this.props) }>Delete</button>
</li>
</ul>
</div>
)
}
}
export default Journal
So this seems to be giving me an error " Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at deleteJournal.js:48"
I checked my server and it seems to be deleting it from there but nothing in the frontend and when I refresh the item is deleted.
What can I do so it automatically deletes the item from the frontend?
I suspect the issue may be with your line
.then(resp => resp.json())
What is the body of the response when you issue the DELETE request? If it's not a valid JSON object, then JavaScript would throw the error you're seeing.
As you're not using the parsed JSON at all, you could conceivably remove that line:
export const deleteJournal = (journal) => {
return dispatch => {
fetch(`http://localhost:3001/journals/${journal.id}` , {
method: "DELETE" })
.then(journal => { dispatch({ type: "DELETE_JOURNAL", journal })
})
}
}
...but you might want to have some of checking that the DELETE method was executed successfully.
How you do that's up to you and your Rails API, but I'd typically expect to see the response have an HTTP status in the 2xx range when something is successfully deleted, and in the 4xx range if something couldn't be deleted (e.g., if the ID wasn't recognised, or there were dependency issues which meant the deletion request was rejected). That feels outside the scope of this question though.
I want to make addons to work to extract the zip file locally like this (here). But I have a problem when making use firefox SDK. Which can not be read zip because somethings wrong when get path of fileinput and errors unsupported format because dataType not ArrayBuffer.
HTML
<input type="file" name="file" id="import" class="hide" />
myscript.js
var fileInput = document.getElementById('import');
fileInput.addEventListener('change', function(e) {
var zipFileToLoad = fileInput.files[0];
var tampJson = [];
JSZip.loadAsync(zipFileToLoad)
.then(function(zip) {
console.dir(zip);
zip.forEach(function (relativePath, zipEntry) {
if(zipEntry.dosPermissions == null){
alert('Permissions trouble !')
}
if(typeof(zipEntry['_data']['compressedContent']) != 'undefined'){
//var text = String.fromCharCode.apply(null, new Uint8Array(zipEntry['_data']['compressedContent']));
var text = new TextDecoder("utf-8").decode(zipEntry['_data']['compressedContent']);
var dec = text.toString();
var json = JSON.parse(dec);
if(json != null){
var keys = ['name', 'description', 'data', 'created_at', 'updated_at'];
keys.forEach(function(key){
if (key in json){
if(key == keys[keys.length - 1]){
tampJson.push(json);
}
}else{
dialog({
title: "Warning",
description: "<b>Wrong format, </b> are you sure to continue?",
yesButton: "yes",
cancelButton: "No",
yesCallback: function() {
$(this).closest('.overlay').removeClass("active");
},
cancelCallback: function() {
$(this).closest('.overlay').removeClass("active");
return false;
}
});
}
});
}else{
alert('format parse gagal');
}
}
});
if(tampJson.length > 0){
saveByImport(tampJson, 0);
}else{
alert('Oops file empty');
}
}, function (e) {
alert('Oops import fail '+ e);
});
Can't error in console. I just can not ArrayBuffer from fileinput.
This script can work in chrome extension but not work in firefox sdk.
So please help me for solving this problem.
I used an older version of jszip in my addon here. You can use the jszip from my repository and use it the way I did. See here - https://github.com/Noitidart/Chrome-Store-Foxified/blob/master/resources/scripts/MainWorker.js#L195
I have a list of teams in my component. These teams are listed in the html-template for the component. I've created add and update functions and they are working, but if I try to access a member variable of team i get the error: NoSuchMethodError: undefined is not a function:
void delete(int id, String name, int onlineId){
Team tempTeam;
html.window.console.info("In delete()");
for(int i = 0; i < teamList.length; i++){
if(teamList.elementAt(i).id == selectedTeam){ // <-- this fails
tempTeam = teamList.elementAt(i);
}
}
...
html.window.console.info("Deleting team: " + name + " succeded!");
}
Here is the component:
#Component(
selector: 'admin-teams-view',
templateUrl: 'packages/fremad/components/admin/teams_view.html',
cssUrl: 'packages/fremad/components/admin/teams_view.css',
useShadowDom: false
)
class ShowAdminTeamsComponent {
List<Team> teamList;
int selectedTeam = -1;
bool isEditing = false;
...
}
Here are the html of interest
<li ng-repeat="team in teamList">
<div class="item-name" ng-click="selectTeam(team.id)">
{{team.name}}
</div>
<div class="item-edit" ng-hide="isActive(team.id)">
<form>
Name:
<input type="text" size="35" ng-model="team.name">
Online ID:
<input type="number" size="15" ng-model="team.onlineId">
<input type="button" class="adminButton redButton" value="delete" ng-click="delete(team.id, team.name, team.onlineId)">
</form>
</div>
</li>
I will be thankful for any help!
From console after doing print(teamList[i]) and print(teamList[i].name):
{id: 1, name: Fremad Famagusta Menn Senior A, onlineId: 30296} js_primitives.dart:25
NoSuchMethodError: undefined is not a function
STACKTRACE:
TypeError: undefined is not a function
at dart.J.get$name$x (http://localhost:8080/fremad/fremad_main.dart.js:40910:39)
at ShowAdminTeamsComponent.delete$3 (http://localhost:8080/fremad/fremad_main.dart.js:34640:22)
at eval (eval at <anonymous> (http://localhost:8080/fremad/fremad_main.dart.js:2922:12), <anonymous>:2:42)
at dart.Primitives_applyFunction (http://localhost:8080/fremad/fremad_main.dart.js:2609:23)
at StaticClosureMap_lookupFunction_closure.call$3 (http://localhost:8080/fremad/fremad_main.dart.js:11389:18)
at ClosureMapLocalsAware_lookupFunction_closure.call$3 (http://localhost:8080/fremad/fremad_main.dart.js:9546:79)
at CallScope.methodClosure$3 (http://localhost:8080/fremad/fremad_main.dart.js:9851:33)
at CallScope.eval$2 (http://localhost:8080/fremad/fremad_main.dart.js:9868:19)
at _UnwrapExceptionDecorator.eval$2 (http://localhost:8080/fremad/fremad_main.dart.js:9359:31)
at _UnwrapExceptionDecorator.eval$2 [as eval$1] (http://localhost:8080/fremad/fremad_main.dart.js:9372:19)
Edit:
This is how my TeamList is loaded:
void loadData() {
tableLoaded = false;
_http.get('rest/team/getTeams.json')
.then((HttpResponse response) {
teamListObject = new TeamList.fromJson(response.data);
teamList = teamListObject.teamList;
tableLoaded = true;
html.window.console.info("Success on loading table");
})
.catchError((e) {
print(e);
tableLoaded = false;
});
}
And this is the class:
class TeamList {
bool empty;
List<Team> teamList;
TeamList(this.empty, this.teamList);
Map<String, dynamic> toJson() => <String, dynamic>{
"emtpy" : empty,
"listObject": teamList
};
TeamList.fromJson(Map<String, dynamic> json) : this(
json['empty'], json['listObject']);
}
You need to change the fromJson in the TeamList class:
TeamList.fromJson(Map<String, dynamic> json) : this(
json['empty'], new List<Team>.from(json['listObject'].map((x) => new Team.fromJson(x))));
Dart does not understand nested classes in that way. You have tried to access the map listObject as a map, not a List.
What exact error message do you get ?
You should try dumping the list and the index in the for loop - using print().
Try to read the answer How to access angular.dart component´s attribute or method
from Günter Zöchbauer
I have
def exception = request.exception.stackTraceLines
in Groovy controller. How can I get the value of the exception in the JavaScript.
If you are adding exception to your return like this.
flash.message = message(exception: 'Error: xxx');
you can get it like this
<div class="message" role="status"> ${flash.message} </div>
just use ${ your flash.your_var_name}
You have multiple options to fix this. When using javascript I usually use a wrapper which can hold the error message/stacktrace. It depends on where and how you want to do the error handling. Example:
def book = new Book(params)
book.validate()
render (contentType: "text/json") {[
"data": book,
"errors": book.hasErrors() ? book.errors : null
]}
Then you can check if "errors" has a value when getting back your JSON to determine if there are errors in the input for instance. (Elvis operator probably works too, book.errors ?: null) Other (uncatched) exceptions I handle in the error callback I usually define in my JavaScript. (jQuery mostly, (with malsup jquery.form.js in this case))
$(function() {
$("form").live("submit", function() {
$(this).ajaxSubmit({
error: function (msg) {
/* Catch hard errors here (500's) */
alert("Error occurred: " + msg);
},
success: function(wrapper) {
if (wrapper.errors != null) {
/* Handle model errors here */
} else {
/* Parse data here */
var book = wrapper.data;
}
}
});
return false;
});
You can also do this
render(template:"book",model:[book:theBook, exception:exception])
Or like this (didnt try, don't know if works)
render(template:"book",model:[book:theBook, exception:exception!=null?exception:""])
and then access from the GSP like this
${exception.getMessage()}