Get record by post title in Wordpress - json

Im trying to figure out the endpoint i need to get a record by its post title in word press. here is how i did it using id
var axios = require('axios');
var data = JSON.stringify({
"acf": {
"twitter": "hello"
}
});
var config = {
method: 'get',
url: URL/wp-json/wp/v2/team/9950', //how can i replace id with post title here
headers: {
'Authorization': 'Basic auth',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
below is how the post title json looks
{
"id": 9950,
"date": "2021-11-11T03:20:35",
"date_gmt": "2021-11-11T03:20:35",
"guid": {
"rendered": "URL/team/john-doe/"
},
"modified": "2022-08-19T14:53:46",
"modified_gmt": "2022-08-19T14:53:46",
"slug": "john-doe",
"status": "publish",
"type": "team",
"link": "URL/team/john-doe/",
"title": {
"rendered": "John Doe" //how do i search for john doe record using title
},
how can i make a get request using title instead of ID

Unfortunately it is not possible by default to search by title.
Though, you can add it to rest api like this:
add_filter( 'rest_team_query', function( $args, $request ){
if ( $title = $request->get_param( 'title' ) ) {
$query = array(
array(
'key' => 'post_title',
'value' => $title,
'compare' => 'LIKE'
));
$args['meta_query'] = $query:
}
return $args;
}, 10, 2 );
Then you can search the title like this in your api call:
/wp-json/wp/v2/team?title=john%20doe

Related

React JSON is undefined

I'm fetching this JSON from an API:
{
"data": {
"email": "test#tre.com",
"inserted_at": "2021-03-30T15:37:06",
"links": [
{
"id": 1,
"title": "My link title",
"url": "http://google.com"
},
{
"id": 2,
"title": "My Youube title",
"url": "http://youtube.com"
}
]
}
}
I'm fetching it this way using Hooks:
export default function Notes() {
const [json, setJSON] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/api/users/1", {
method: "GET"
})
.then((response) => response.json())
.then((json) => {
// console.log(data);
setJSON(json);
})
.catch((err) => {
console.error(err);
});
}, [setJSON]);
Then I try to show it like this:
return (
<>
<div className="content">
{JSON.stringify(json)}
<h1>{json.email}</h1>
</div>
</>
);
The line {JSON.stringify(json)} shows the JSON.
But the line <h1>{json.email}</h1> doesn't show anything.
I don't know why that happens and how can I access my variables.
Thanks . I appreciate any help
Is the data in the form of an array or an object?
You defined the initial state as and array ad hence you cannot do
// you can't do json.email if you expect the response as and array
const [json, setJSON] = useState([]);
change it to
const [json, setJSON] = useState({});
if it is an object. Then in the template do
{json.data && <h1>{json.data.email}</h1>}
<h1>{json.data && json.data.email}</h1>
instead of
<h1>{json.email}</h1>

Cant access key values from an Object in Reactjs after fetching

I have a user details page in Reactjs where I'm fetching the user details and populating it to the corresponding fields. But I'm not able to access key values from the user object.
My sample code is
function EditProfile(props) {
const [user, setUser] = useState()
useEffect(() => {
const fetchUserInfo = async () => {
const profileConfig = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + auth.token
}
};
fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
.then(response => response.json())
.then(response => {
console.log("response: ", response.user);
if (response.success === true) {
setUser(response.user)
} else {
alert(response.message)
}
},
(error) => {
alert('User fetching faied: ' + error)
})
}
fetchUserInfo()
}, [])
return (
<div>{user.name}</div>
)
}
The response from the server (user object is)
{
"status": true,
"_id": "5ecfdc403165f709b49a4a0e",
"name": "Anand OL",
"gender": "male",
"dob": "2020-12-13T00:00:00.000Z",
"email": "anand#gmail.com",
"phone": "1234567890",
"createdAt": "2020-05-28T15:44:00.700Z",
"updatedAt": "2020-06-01T08:38:37.902Z",
"__v": 136,
"image": "5ecfdc403165f709b49a4a0e_Image.png"
}
when I try to access name from the user object like user.name
I'm getting an error user is not defined
You need to provide some initial state to display (or conditionally render) while the fetch is occuring.
const [user, setUser] = useState(); // <-- user is undefined!!
Conditionally render UI
return <div>{user && user.name}</div>;
or
return user ? <div>{user.name}</div> : null;
Note: Use caution with the former as not all falsey values are created equal, i.e. Consider return <div>{value && value.property}</div>, if/when value = 0 a falsey value, then a "0" will actually be rendered.
Or you can provide some default state
const [user, setUser] = useState({ name: '' });

Iterate a JSON array by a key value in react-native

Is there anyway to get a value in an object from a json array. I need to get a value from an object based on another value.
I have my code like:
export default class StandardComp extends Component {
constructor(props) {
super(props)
this.state = {
id: '',
email: 'abc#gmail.com',
dataSource: []
};
}
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({dataSource: responseJson})
//dunno what to do here
})
.catch((error) => {
console.error(error);
})
}
}
My "responseJson" is something like this. Then providing the key value (abc#gmail.com), how could I get the string "abcdef"?
[
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
}
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
]
Thank you in advance.
Find the element that matches email and return the id.
array::find
const data = [
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
},
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
];
const findIdByEmail = (data, email) => {
const el = data.find(el => el.email === email); // Possibly returns `undefined`
return el && el.id; // so check result is truthy and extract `id`
}
console.log(findIdByEmail(data, 'cat#gmail.com'));
console.log(findIdByEmail(data, 'abc#gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));
The code will depend on how you get the value abc#gmail.com.
You'll probably need to pass it in as an argument to componentDidMount via a prop? Or extract it to a separate function. It just depends.
Something like this is the most basic way I'd say.
const value = responseJson.filter(obj => obj.email === 'abc#gmail.com')[0].id
Here it is implemented in your class.
export default class StandardComp extends Component {
...
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: responseJson })
const { email } = this.state
const value = responseJson.filter(obj => obj.email === email)[0].id
})
.catch((error) => {
console.error(error);
})
}
}

Try to get key values recursively from JSON in Angular 5

I want to retrieve all the key values from a JSON file. For example in :
{
"total_count": 6,
"incomplete_results": false,
"items": [
{
"url": "https://api.github.com/repos/Samhot/GenIHM/issues/6",
"id": 293237635,
"number": 6,
"title": "Rechercher des documents",
"user": {
"login": "Samhot",
"id": 7148311
]
}
I would like to get :
["total_count", "incomplete_results", "items", "url", "url", "number", "title", "user", "login", "id"]
I have a function which return the content of my JSON in an observable :
getConfig(): Observable<any> {
return this.http.get<any>(this.myURL);
}
After that the data are reformated with .map to get only the keys with the Object.keys() function :
merge()
.pipe(
startWith({}),
switchMap(() => {
return this.getConfig();
}),
map(data => {
return Object.keys(data.items[0]);
}
)
)
.subscribe(data => {
this.dispo = data;
});
My problem is that i get only the keys that are in the level of the JSON I told
(data.items[0]) and not the ascendants or the descendants.
Of course I can create multiple requests but it asks to know in advance the structure of the JSON, what I want is to make it generic ...
How can I do to have an array with with all of my keys regardless of the structure of the JSON ?
Thanks in advance !
You would need to do a recursive function like:
function getDeepKeys(obj) {
const keys = Object.keys(obj);
const childKeys = keys
.map(key => obj[key])
.map(
value =>
Array.isArray(value)
? getDeepKeys(value[0])
: typeof value === "object"
? getDeepKeys(value)
: []
)
.reduce((acc, keys) => [...acc, ...keys], []);
return [...keys, ...childKeys];
}
const obj = {
total_count: 6,
incomplete_results: false,
items: [
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
},
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
}
]
};
console.log(getDeepKeys(obj));
Which then you would use like map(getDeepKeys). Note that this function assumes all the items in your array have the same schema.

Angular2, get data from REST call

I'm triyng to get data from json file by a id, by I'm getting all the content.
Here the JSON:
[
{ "id": "1", "name": "Carlos", "apellidos":"López", "edad":"30", "ciudad":"Hospitalet" },
{ "id": "2", "name": "Arantxa", "apellidos":"Pavia", "edad":"24", "ciudad":"Barcelona" },
{ "id": "3", "name": "Didac" , "apellidos":"Pedra", "edad":"muchos", "ciudad":"Cornellà" },
{ "id": "4", "name": "Daniel" , "apellidos":"Farnos", "edad":"nolose", "ciudad":"Barcelona" }
]
Service:
private usersUrl = 'app/users.json';
getUser(id: String): Observable<User>{
let body = JSON.stringify(
{
"token": "test",
"content": {
"id": id
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
headers: headers,
body : body
});
return this.http.get(this.usersUrl, options)
.map(res => res.json()).catch(this.handleError);
}
Angular Component:
ngOnInit(){
this.route.params.subscribe(params => {
let id = +params['id'];
this.apiService.getUser(id).subscribe( (res) => { console.log(res); } );
})
}
Console.log:
Array[4]0: Object1: Object2: Object3: Objectlength: 4__proto__: Array[0]
Is the JSON bad?
Thanks.
Because you didn't filter the result by id.
.map(res => res.json())
.map(x > x.find(x => x.id == id) // filter by selected id
.catch(this.handleError);