Iterate Rails Array of Objects in React-Native - ruby-on-rails

I'm trying to iterate an Array of Objects (retrieved from an ActiveRecord query) in a react-native app to render inside a table.
ActiveRecord query
def list
render json: Client.select('name, created_at, id').order('created_at DESC')
end
And this is how i am obtaining the data from the API (react):
getStatus() {
fetch(global.api_clients, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + global.token,
},
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
clients: responseJson
});
})
.catch((error) => {
console.error(error);
});
}
Query output
Array [
Object {
"created_at": "2019-05-08T11:33:06.573Z",
"id": 1,
"name": "Francesco",
},
]
Rendering
render() {
const state = this.state;
const listItems = state.clients.map((link) =>
<Row data={link.name} textStyle={styles.text}/>
);
console.log(this.state.clients);
return (
<View style={styles.container}>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
<Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
{listItems}
</Table>
</View>
)
}
undefined is not a function (near '...data.map...')

Found it.
Error was in Row data, since it pretends an array.
Solved this way:
<Row data={[link.name, link.id, link.name]} textStyle={styles.text}/>

Related

NativeScript-Angular - POST formdata to Wordpress ContactForm7 API

Hello everyone and thanks in advance ...
I'm trying to use the Contact Form7 APIs to fill in and submit a form from an Angular NativeScript App.
I have tried different solutions but I always get the same error response.
{"into":"#","status":"validation_failed","message":"Oops, there seems to be some error in the fields. Check and try again, please.","invalidFields":[{"into":"span.wpcf7-form-control-wrap.nome","message":"Attention, this field is required!","idref":null},{"into":"span.wpcf7-form-control-wrap.mail","message":"Attention, this field is required!","idref":null}]}
In the example I have entered static values ​​in the body for convenience
Help me ;(
attempt 1
onTappedInvia(): void {
fetch("http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
nome: "Test API",
mail: "test#test.test"
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
attempt 2
deliverForm() {
var formData: any = new FormData();
formData.append('nome', "Test API");
formData.append('email', "test#test.test");
formData.append('your-message', "Test API");
this.submitted=true;
console.log(formData);
this.formService.create(formData)
.subscribe(
data => {
console.log('Invoice successfully uploaded');
console.log('Error'+ JSON.stringify(data));
},
error => {
console.log('Error'+ JSON.stringify(error));
});
console.log('USCITO');
}
and formService
const HttpUploadOptions = {
headers: new HttpHeaders({ "Content-Type": "multipart/form-data;" })
}
#Injectable({
providedIn: 'root'
})
export class FormService {
constructor(
private HttpClient: HttpClient
) { }
create(formData){
return this.HttpClient.post('http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback', formData, HttpUploadOptions)
}
}
The problem was with the Content-Type. i tried with application/x-www-form-urlencoded and it works!
fetch("http:www.aficfestival.it/wp-json/contact-form-7/v1/contact-forms/5173/feedback?", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: form
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}

Response Isn't Converting To JSON

I'm trying to take info from a React form and post it to my Rails database, but I get an error "unexpected token '<' at position 0" which means my response is still HTML and not JSON.
Here's my code:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => response.json())
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
}
Is there a reason why it's not converting to JSON?
Additionally, I don't seem to be able to drop debugger into my code, or at least in this function - do I need to import it or something?
I'm thinking that your server is sending you back HTML and then you are trying to parse it in response.json()
use a try/catch in this block:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => {
try {
return response.json()
} catch(error) {
console.error(error);
}
})
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}

antd Table with switch component

Is it possible to get row information by switching the switch in ant design table?
https://codesandbox.io/s/mmvrwy2jkp
Yes, the second argument of the render function is the record.
you can do this
{
title: 'switch',
dataIndex: 'age',
key: 'age',
render: (e, record) => (< Switch onChange={() => handleSwitchChange(record)} defaultChecked={e} />)
}
This is how I dealed with the switch component on each row item when using Ant design. Maybe this could give you some hints.
Table Columns
const COLUMN =
{
title: 'Status',
key: 'status',
dataIndex: 'status',
// status is the data from api
// index is the table index which could be used to get corresponding data
render: (status, record, index) => {
const onToggle = (checked) => {
status = checked;
onActiveUser(index, status);
};
return (
<Space>
<Switch defaultChecked={status} onChange={onToggle} />
</Space>
);
},
},
const onActiveUser = (index, status) => {
axios.patch({ id: users[index].id }, { is_active: status })
.then((response) => {
console.log(response);
})
.catch(() => {
console.log('Failed!');
});
};

Cannot consume rest api (Web Api) from component React

I'm developing a web, it consume a rest api, this api rest is build in asp.net as a Web Api. My issue is present when try consume an endpoint, because use fetch, but this not show any.
this is my code
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
class BundleShipping extends React.Component {
constructor(props) {
super(props)
this.state = {
pickTicket: '',
Pallets: [],
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ pickTicket: event.target.value });
}
handleSubmit(event) {
this.GetParametersPickTicket('016683O01', 'en-US', 'e3eda398-4f2a-491f-8c8e-e88f3e369a5c')
.then((responseData) => { this.setState({ Pallet: responseData.Data.Pallet }) })
.then((response) => console.log(response))
}
GetParametersPickTicket(PickTicket, language, Plant) {
console.log(PickTicket)
console.log(language)
console.log(Plant)
return fetch('http://localhost:55805/api/GicoBundleWA/GetParametersPickTicket', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => { console.log(JSON.stringify(responseJson)) })
.catch((err) => console.log(err))
}
render() {
const columns = [{
dataField: 'PalletNumber',
text: 'Estibas Cargadas'
}, {
dataField: 'Quantity',
text: 'Cantidad'
}, {
dataField: 'Bundles',
text: 'Bultos'
}, {
dataField: 'Date_Time',
text: 'Fecha de carga'
}];
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<div className="col-lg-2 col-md-2 col-xs-3">
<label>Shipping</label>
</div>
<div className="form-group col-lg-5 col-md-5 col-xs-5">
<input type="text" value={this.state.pickTicket} onChange={this.handleChange} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Pick Ticket" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<BootstrapTable keyField='PalletNumber' data={this.state.Pallets} columns={columns} />
</div>
)
}
}
but onclick in the button not show data in console, only show it
016683O01 VM494 bundle.js:67423
en-US VM494 bundle.js:67424
e3eda398-4f2a-491f-8c8e-e88f3e369a5c VM494 bundle.js:67425
Navigated to http://localhost:3000/xxxx?
react-dom.development.js:17286 Download the React DevTools for a better development experience:
I did some tests for discover my error, for example execute code directly in console so:
function GetParametersPickTicket(PickTicket, language, Plant) {
console.log(PickTicket)
console.log(language)
console.log(Plant)
return fetch('http://localhost:xxx/api/XXX/YYYY', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => { console.log(JSON.stringify(responseJson)) })
.catch((err) => console.log(err))
}
GetParametersPickTicket('016683O01', 'en-US', 'e3eda398-4f2a-491f-8c8e-e88f3e369a5c')
and this one if it shows my answer json.
Additionally, i resolved issue with cors, and try with postman and it show
access-control-allow-origin β†’*
I don't understand, why in component react does not show any result
First problem is that your method GetParametersPickTicket simply logs the received json, but it never returns it. So, the consumer of this method will simply receive an empty resolved promise. See my comment "This part was missing" in the following snippet:
GetParametersPickTicket(PickTicket, language, Plant) {
return fetch('http://localhost:55805/api/GicoBundleWA/GetParametersPickTicket', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => {
console.log(JSON.stringify(responseJson)
return responseJson // <-- This part was missing
})
.catch((err) => console.log(err))
}
Second problem is that you're getting redirected when your form is submitted, am I right? Thus, you need prevent this default form behaviour by adding a event.preventDefault() in the beginning of your handleSubmit method:
handleSubmit(event) {
event.preventDefault()
// ... other code here
}

JqueryUI Autocomplete not working in CakePHP 2.0

My autocomplete is not working and I can't spot the error.
Jquery:
<script>
$(function() {
$('#autoComplete').autocomplete({
//source: "/groceries/items/autoComplete", ///This works but response isn't formatted correctly'
//dataType: "json"
minLength: 2,
source: function( request, response ) {
$.ajax({
url: "/groceries/items/autoComplete",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
response( $.map( data, function( el ) {
return { label: el.id, value: el.name }
}));
}
});
}
});
});
Controller:
public function autoComplete() {
Configure::write('debug', 0);
$this->layout = 'ajax';
$query = $_GET['term'];
$items = $this->Item->find('all', array(
'conditions' => array('Item.name LIKE' => $query . '%'),
'fields' => array('name', 'id', 'category_id'),
'group' => array('name')));
$this->set('items', $items);
}
Form:
<p>
<?php echo $this->Form->create('Item', array('model'=>'item','action' => 'addItem', 'name'=>'AddItem'));?>
<?php echo $this->Form->text('Item.name', array('size'=>'30', 'id'=>'autoComplete', 'autocomplete'=>'off')); ?>
<?php echo $this->Form->text('Item.category_id', array('type'=>'hidden', 'value'=>'0')); ?>
<?php echo $this->Form->text('Groclist.id', array('type'=>'hidden', 'value'=>$groclist['Groclist']['id'])); ?>
<?php echo $this->Form->end('Add'); ?>
</p>
Response:
0: {Item:{name:Cake, id:6, category_id:null}}
1: {Item:{name:Carrot Cake, id:9, category_id:null}}
2: {Item:{name:Carrots, id:8, category_id:null}}
3: {Item:{name:Casserole, id:11, category_id:null}}
4: {Item:{name:Cauliflower, id:10, category_id:null}}
Edited for clarification.
I realize JqueryUI expects label and value and that map should rearrange them, but for some reason it's not. Any ideas?
I found an even better solution. This is done completely in the controller. No view required.
public function autoComplete() {
Configure::write('debug', 0);
*$this->autoRender=false;*
$this->layout = 'ajax';
$query = $_GET['term'];
$items = $this->Item->find('all', array(
'conditions' => array('Item.name LIKE' => $query . '%'),
'fields' => array('name', 'id', 'category_id'),
'group' => array('name')));
*$i=0;
foreach($items as $item){
$response[$i]['value']="'".$item['Item']['id']."'";
$response[$i]['label']="'".$item['Item']['name']."'";
$i++;
}
echo json_encode($response);*
}
What if you reduce the array that is being returned by the Items model. So instead of $this->set('items', $items); you return the json encoded results like so:
foreach($items as $item) {
$data[] = $item['Item'];
}
$data = json_encode($data);
echo $data;
exit;
This is inside the auto_complete method in the controller.
UPDATE:
When querying for Cake for example, it would return a result like so:
[
{"name":"Cake Batter","id":"1","category_id":"3"},
{"name":"Cake Mix","id":"2","category_id":"3"}
]
if you are not wanting to return the json, you could just return $data without the json encoding.
Format Update:
I am not certain if this is to "sloppy", but you could change the foreach loop to:
foreach($items as $item) {
$data[]= array(
'label' => $item['Item']['name'],
'value' => $item['Item']['id']
);
}
Looks like you forgot the Item:
response($.map( data, function( el ) {
return { label: el.Item.id, value: el.Item.name }
});
You can also do it in the server side using Set:
$this->set('items', Set::extract('/Item', $items));

Resources