React add image field and save in pouchdb - reactjs

I want to add a file/image field to my current field and save in pouchdb. Is there any cool way to handle this?
Here's what I have currently:
this.newInfo = {
id: uuid(),
createdAt: toDate(),
Info: {
name: '',
dob: '',
designation: ''
}
}
this.state = {
doc: this.newInfo
}
In another file:
submitInfo (event) {
event.preventDefault()
let Info = Object.assign({}, this.props.doc)
if (!Info._id) {
Info._id = Info.id
}
console.log('About to post to pouch...', Info._id)
// Save to pouchdb
this.db.put(Info , (err, result) => {
if (!err) {
console.log('Successfully posted to pouchdb!')
this.props.clearCurrentDoc()
} else {
console.log('Error saving to pouch...')
console.log(err)
}
})
}
The form:
<fieldset>
<legend>Info</legend>
<input name='name'
value={props['name']}
type='text'
placeholder='Enter Name'
onChange={handleChange}
/>
<input name='dob'
value={props['dob']}
type='date'
placeholder='Date of Birth'
onChange={handleChange}
/>
<input name='designation'
value={props['designation']}
type='text'
placeholder='Designation'
onChange={handleChange}
/>
</fieldset>
I want to add one more field for saving images. Maybe call it picture. Sorry, I can't put the entire code but everything else is working fine. I just need to add a field that will browse for image or file and save it with the existing ones.

I've got a good sample on jsbin that should help you to sort through this. There is an input button that let's you select an image and then submit this to PouchDB. If you are using CouchDB the code is also there to replicate the data to CouchDb. The general idea is to use something like this:
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="file" name="file" />
<script>
var field1= window.document.reportform.field1.value;
var field2= window.document.reportform.field2.value;
var inputFile = document.querySelector("#file");
getFile = inputFile.files[0];
var myDoc = {
_id: new Date().toISOString(),
field1: field1,
field2: field2,
_attachments: {
"file": {
content_type: getFile.type,
data: getFile
}
}
}
db.put(myDoc, function(err, response) {
if (err) {
return console.log(err);
} else {
console.log("Document created Successfully");
}
});
db.replicate.to(remote);
}
</script>
JSbin: PouchDB image select and put()
I have not been able to get to work. I have asked on stackoverflow and the PouchDB Slack channel. Some suggestions have been made but so far I haven't gotten it working.
The PouchDB documentation is very good. PouchDB Attachments Guide

Related

How would I iterate through array and display input boxes based on values?

I am new to react and I created I have a json like this:
const parent: [{name:will, kids['child1', 'child2']}
{name: 'kia' kids['child1']}
{name: 'jim', kids['child1', 'child2']}]
I am having trouble accessing the values with this json. I am trying to create a list with all the name values in of array so I can put it in a dropdown but I keep getting 'undefined' when i try to print the list in my console.log
Also when I click the name I want to create input boxes based of the length of the kids list of the name selected. So for instance if I click 'will' in the dropdown, two input boxes will form with 'child1' and 'child2' being in both input boxes. but if i click "kia", one input box will form that already has "child 1" in it. Any ideas? I have having a lot of trouble accessing the values.
this is my attempt so far:
import Dropdown from 'react-dropdown';
parent: [{name:will, kids['child1', 'child2']}
{name: 'kia' kids['child1']}
{name: 'jim', kids['child1, 'child2']}]
class AppEX extends React.Component {
constructor() {
super();
this.state = {
parentnamelist: []
parentname: null
}
}
render() {
namelist: []
this.state.parent.map((e, key) => {
namelist.push({value:e.name,label:e.name})
})
return (
<select name="select" onChange={this.namelist}>
{num.map(function(n) {
return (<option value={n} selected={this.state.selected === n}>{n}</option>);
})}
</select>
any ideas?
There are various problems here.
The parent list was not well formatted, is should look like this:
const parent = [
{ name: "will", kids: ["child1", "child2"] },
{ name: "kia", kids: ["child1"] },
{ name: "jim", kids: ["child1", "child2"] }
]
You are using map in your render method to push parent names into a new list called namelist but you have to use forEach. map transforms a list while forEach does something to each member.
const namelist = [];
this.state.parent.forEach(e => {
namelist.push({ value: e.name, label: e.name });
});
Now render return:
The onChange handler must be a function, since you want to track the selected parent, I guess you want to save it to your state:
handleParentChoice = e => {
e.persist();
this.setState({
parentname: e.target.value
});
};
Then
return (
<div>
<select name="select" onChange={this.handleParentChoice}>
{namelist.map(n => (
<option key={n.value} value={n.value}>{n.label}</option>
))}
</select>
<br />
{this.state.parentname && // Shows below stuff only if parentname is not null
this.state.parent
.find(p => p.name === this.state.parentname) // Find the parent based on the saved name, then map the kids into input tags
.kids.map(k => <input key={k} type="text" />)}
</div>
);
Also, when you map something, every child should have a key prop.
See the code working here

How to show option name in Ant Design Select when using setFieldsValue

I'm using a component from Ant Design and recently I added a button to select all options. The functionality is ok but in the field it shows the option keys or ids instead of showing the option names.
My question is, is there any way to show the option names when using setFieldsValue method in a multi-select component?
I have tried pushing an object with different properties (id, name, key, value, title, etc) in this part selecteds.push(kid.id); but none of those works.
My select funtion looks like this
selectAllKids = () => {
const { kids } = this.props;
let selecteds = [];
kids.map(kid => {
selecteds.push(kid.id);
});
this.props.form.setFieldsValue({
kids: selecteds
});
};
and my component:
{getFieldDecorator("kids", {
rules: [
{
required: true,
message: "Selecciona alumnos"
}
]
})(
<Select
size="large"
mode="multiple"
placeholder="Selecciona alumnos"
loading={kidsLoading}
>
{kids.map(kid => (
<Option key={kid.id}>{kid.name}</Option>
))}
</Select>
)}
My current result is:
My expected result is:
Thanks in advance!
You should map to name and not to id:
this.props.form.setFieldsValue({
kids: kids.map(({ name }) => name)
});

Angular Js how to get checkbox value on edit and submit?

<input type="checkbox" ng-model="mail.email" name="email"
ng-true-value="'mail.email'" ng-false-value="'0'">
This is my code while im going to edit i need to fetch the value from database but if i click the checkbox it shows the following response
{
regid: "NADr333434",
email: "mail.email",
altemail: "mail.altemail",
htmlcontent: "<b>kuhiuhioh oih oihih</b>"
}
I need the output as the follwing format how to get this
{
regid: "NADr333434",
email: "test#gmail.com",
altemail: "alternate#test.com",
htmlcontent: "<b>kuhiuhioh oih oihih</b>"
}

kendo ui autocomplete - set data on load

I have a textbox for which I added kendoAutoComplete function. This is working fine. However, I wanted to set some value to this textbox upon the page load (I get the value from DB). With KendoAutoComplete, I am unable to set this.
I can either implement KendoAutoComplete or set datsource. Both of them work fine separately. Where as, if I include the code related to both - it doesnt work. Below is the code. Can you please throw me some inputs if you have come across this issue?
myController.js
$("#txtPartNumbers").kendoAutoComplete({
dataSource: {
serverFiltering: true,
enforceMinLength: true,
transport: {
read: {
url: ApiBaseUrl.val + 'inventoryLocation/getParts',
type: "get",
dataType: "json",
data: function () {
return { partNumber: $scope.autoCompleteText }
}
}
},
},
change: function(e) {
$scope.autoCompleteText = this.value();
},
filter: "startswith",
//placeholder: "Select Inventory Parts..",
minLength: 3,
separator: ", "
});
cshtml
<div class="sectionFloatLeft">
<label>Part Number(s):</label><br />
<input id="txtPartNumbers" type="text" ng-model="filterByPartNumbers" class="form-control filterTextArea" style="width: 300px;height:80px;" placeholder="Enter Part Numbers (Comma sepatared)" />
</div>
I am setting "filterByPartNumbers" value in my controller
....
var data = getDataFromDB();
$scope.filterByPartNumbers = data.partNumbers;
...
Appreciate you help.
I was able to set the value as below:
$("#txtPartNumbers").data("kendoAutoComplete").value(data.partNumbers);
Thanks!

VUEjs templates multiple selectboxes

So, I'm assigned to work with vue at work, but VUE and I aren't friends yet. Currently I'm facing an issue that I don't know how to resolve - I'll explain it the best I can with the limited VUE knowledge I possess.
Simplistically I have a vue component, which looks like this:
Vue.component('input-checkboxes', {
template: '#input_checkboxes',
props: ['id', 'label', 'list', 'required', 'readonly']
});
Then I have a template that looks like this:
<template id="input_checkboxes">
<div>
<div>{{ label }}</div>
<div>
<label v-for="list_item in list">
<input type="checkbox" v-model="value" :name="id" :required="required" :readonly="readonly" value="{{ list_item.name }}"> {{ list_item.name }}
</label>
</div>
</div>
</template>
Then I have a rather large vue instance that I'll paste the relevant parts of here.
This variable is being created:
var some_form = {
form : {
Endless: '',
Amounts: '',
Of: '',
Names: '',
In: '',
The: '',
Form: '',
THIS-ONE: ''
}
};
var vm = new Vue({
el: '#form_product',
data: $.extend({
someStuff : 'some values',
someLists : {}
}, some_form),
ready: function() {
this.getLists(); // Fetches alot of lists
},
methods: {
this.$http.get(
framework.url('api','getLookupLists')
).then(function (response) {
this.lists = response.body;
this.pageLoading = false;
}.bind(this));
}
In the end I have my html page that amongst loads of other fields, that works very well, has this:
<input-checkboxes
id="THIS-ONE"
label="A Fitting Label"
:value.sync="form.SomeID"
:list="lists.AnAppropriateList">
</input-checkboxes>
So, that's the gist of the setup. I have numerous other components like input-text, that works just fine (someone else made it before I did), I even created other components by copying his way, and just changing some elements.
I cannot get checkboxes to work, I think my problem is that there are numerous inputs, and that I don't know how to bind the results of those inputs to my VUE instance.
I really hope this makes sense, because I would really like some pointers on how to get on... Maybe if someone duplicated this setup really simplistic and showed how the array of values from the checkboxes could be bound to the vue instance?
There are a couple of mistakes you are (or might be) making.
First of all, the value prop you pass down has to be an array (seems
like it's a string from your example)
value is not correctly set, you need to set it by doing :value="someValue"; you can't have curlies in an attribute.
Lastly, value should probably be the id of the item and not the name. You have a chance of a collision if you use the name.
Bonus: you don't need to use :name at all (unless you are submitting the form server side...? But I can't see why you would do that.)
Here's a simple working example to sum this up:
HTML
<label v-for="list_item in list">
<input type="checkbox" v-model="value" :required="required" :readonly="readonly" :value="list_item.id"> {{ list_item.name }}
</label>
JS
var app = new Vue({
el: 'main',
data: function () {
return {
value: [],
label: 'Label name',
readonly: false,
required: true,
list: [
{
name: 'Item 1',
id: 'item1'
},
{
name: 'Item 2',
id: 'item2'
}
]
}
}
})
I've also made a bin for you to try it out.

Resources